Android:将字符串转换为整数

38

我只是想把一个由条形码扫描器生成的字符串转换为整数,以便我可以通过获取余数来生成一组整数。到目前为止,我尝试过:

int myNum = 0;

try {
    myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {

} 

Integer.valueOf(mystr);

int value = Integer.parseInt(string); 

第一个会给我一个错误:字符串类型没有定义getText()方法,而最后两个没有任何编译错误,但当它们被调用时应用程序立即崩溃。我认为这可能与我的条形码扫描意图方法有关,但我把它放到OnCreate中仍然出现了错误。


你能打印出 myString 的值吗?你确定它只包含一个整数(仅为数字,不大于 2^31)吗?当应用程序崩溃时,是否会收到任何异常? - trutheality
嘿,你知道如何将字符串转换为游标吗?我看到了这个(https://dev59.com/_mkw5IYBdhLWcg3waZtW),但我无法理解它。 - Tushar Gogna
9个回答

48

修改

try {
    myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {

9
它已经是一个字符串了吗?去掉getText()调用。
int myNum = 0;

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
  // Handle parse error.
}

8
您只需要编写一行代码将您的字符串转换为整数。
 int convertedVal = Integer.parseInt(YOUR STR);

3

使用正则表达式:

int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));

输出:

i=123;
j=123;
k=123;

如果你想用那种方式做的话,那就使用\D+而不是[\D],但如果有浮点数,它会变得混乱。例如12.34将导致1234。所以我宁愿使用replaceAll("[^\d.]+","")。 - FlorianB

2

使用正则表达式:

String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""))

输出:i=1234;

如果您需要第一个数字组合,则应尝试以下代码:

String s="abc123xyz456";
int i=((Number)NumberFormat.getInstance().parse(s)).intValue()

output: i=123;


我使用了两种方法,但第二种方法虽然有效,但它完全改变了值!字符串值“4307764028”=> 12796732。 - Prasad

1
条形码通常由大量数字组成,所以我认为您的应用程序崩溃是因为您正在尝试转换为int的字符串大小。您可以使用BigInteger
BigInteger reallyBig = new BigInteger(myString);

1
如果您的整数值为零或以零开头(此时第一个零将被忽略),则无法转换为字符串。尝试进行更改。
int NUM=null;

int不是一个对象,因此不能为null! - Nemesis
如果是这样的话,我想微软只在我的Visual Studio中启用了它。 - ABi

0

试一下这个

String t1 = name.getText().toString();
Integer t2 = Integer.parseInt(mynum.getText().toString());

boolean ins = myDB.adddata(t1,t2);

public boolean adddata(String name, Integer price)

这是将mynum插入数据库的方法,布尔部分是如何在您的数据库中插入数据,然后创建if-else条件来检查是否已插入数据,请注意,在您的databasehandler中确保您的添加数据具有正确的参数。 - Dev_android

-1

// 将字符串转换为整数

// String s = "fred";  // use this if you want to test the exception below


String s = "100"; 
try
{
  // the String to int conversion happens here
  int i = Integer.parseInt(s.trim());

  // print out the value after the conversion
  System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
  System.out.println("NumberFormatException: " + nfe.getMessage());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接