我有一个返回类型是字符串的方法下面是方法
public String getHwIdentifier();
现在我正在使用这种方法..
String s = till.getHwIdentifier();//return type of this method is string
我想把它转换成这样的整数
Int i = till.getHwIdentifier();
请告知如何取整数意味着如何转换它..
从 Integer 类尝试 parseInt 。
Integer.parseInt(till.getHwIdentifier());
NumberFormatException
但请注意,如果字符串不是有效的整数表示,它会抛出
使用类的parseInt(String s)
方法,Integer
该方法String
将其转换int
为数字或抛出NumberFormatException
如下:
int i = Integer.parseInt(till.getHwIdentifier());
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.
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 。
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.