在Android上将字符串转换为整数

詹姆斯·安德鲁:

如何将字符串转换为整数?

我有一个文本框,我让用户输入一个数字:

EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();

并将该值分配给字符串hello

我想将其转换为整数,以便获得他们键入的数字;稍后将在代码中使用它。

有没有办法得到EditText一个整数?那会跳过中间人。如果不是,则将字符串转换为整数就可以了。

乔恩:

请参阅Integer类和静态parseInt()方法:

http://developer.android.com/reference/java/lang/Integer.html

Integer.parseInt(et.getText().toString());

您可能需要NumberFormatException在解析时发现问题,所以:

int myNum = 0;

try {
    myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
   System.out.println("Could not parse " + nfe);
} 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章