2012-10-31 306 views
0

我有返回类型的字符串下面是该方法关于结果的铸造

public String getHwIdentifier(); 

现在我用这个方法的方法..

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

我要投它在整即是这样的

Int i = till.getHwIdentifier(); 

请指教如何利用整数指怎么投呢..

+1

你可能是int(java原始类型)或Integer而不是Int? –

回答

1

尝试从Integer类parseInt。

Integer.parseInt(till.getHwIdentifier()); 

不过,别忘了,它会抛出NumberFormatException如果字符串不是有效的整数表示

1

使用parseInt(String s)方法Integer类需要String并将其转换为int,如果它是一个数字或抛出NumberFormatException这样的:

int i = Integer.parseInt(till.getHwIdentifier()); 
0

没有Java类/类名为Int。有int类型,它封装了Integer类。

您可以分析在String整数到int值与Integer.parseInt("1234");,或Integer.valueOf("1234");得到Integer值。但请注意,如果String不代表整数,您将获得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) 
    { 
     //... 
    } 

注意:您可以使用Integer a = Integer.decode(s);,但Integer c = Integer.valueOf(s);是优选的,如果可能的话也不会创建新的对象。

0
String s = till.getHwIdentifier(); 
int i = Integer.parseInt(s); 

确保您的字符串的形式为整数。如果你的字符串包含xyz,那么你将得到一个java.lang.NumberFormatException。