0

我有一个返回类型是字符串的方法下面是方法

public String getHwIdentifier();

现在我正在使用这种方法..

String s = till.getHwIdentifier();//return type of this method is string

我想把它转换成这样的整数

Int i = till.getHwIdentifier();

请告知如何取整数意味着如何转换它..

4

5 回答 5

1

从 Integer 类尝试 parseInt 。

Integer.parseInt(till.getHwIdentifier());

NumberFormatException但请注意,如果字符串不是有效的整数表示,它会抛出

于 2012-10-31T11:49:31.850 回答
1

使用类的parseInt(String s)方法,Integer该方法String将其转换int为数字或抛出NumberFormatException如下:

int i = Integer.parseInt(till.getHwIdentifier());
于 2012-10-31T11:49:32.437 回答
0
String s = till.getHwIdentifier();
int i = Integer.parseInt(s);

Make sure that your string is in the form of an integer. If your string contains xyz then you will get a java.lang.NumberFormatException.

于 2012-10-31T19:37:51.160 回答
0

String传递to的实例Integer.valueOf(String s)。所以在你的情况下:

Integer i = Integer.valueOf(till.getHwIdentifier);

有关详细信息,请参阅http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28java.lang.String%29 。

于 2012-10-31T11:51:09.833 回答
0

There is no Java type/class named Int. There's int type and it's encapsulating Integer class.

You can parse an integer in a String to the int value with Integer.parseInt("1234");, or get the Integer value with Integer.valueOf("1234");. But notice if the String doesn't represent an integer you'll get a NumberFormatException.

    String s = till.getHwIdentifier();//return type of this method is string;
    try
    {
      Integer a = Integer.valueOf(s);
      int b = Integer.parseInt(s);
    }
    catch (NumberFormatException e)
    {
      //...
    }

Note: You could use Integer a = Integer.decode(s);, but Integer c = Integer.valueOf(s); is preferred as it won't create new objects if possible.

于 2012-10-31T11:57:16.210 回答