如何将字符串转换为整数?
我有一个文本框,让用户输入一个数字:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
这个值被赋值给字符串hello。
我想把它转换成一个整数,这样我就能得到他们输入的数字;稍后将在代码中使用它。
是否有方法将EditText转换为整数?这样就跳过了中间人。如果不是,字符串到整数就可以了。
如何将字符串转换为整数?
我有一个文本框,让用户输入一个数字:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
这个值被赋值给字符串hello。
我想把它转换成一个整数,这样我就能得到他们输入的数字;稍后将在代码中使用它。
是否有方法将EditText转换为整数?这样就跳过了中间人。如果不是,字符串到整数就可以了。
当前回答
你也可以只写一行:
int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));
从执行顺序读取
使用findViewById(R.id.button1)获取视图 使用((Button)______)将视图转换为按钮 调用.GetText()从Button获取文本条目 调用.toString()将字符变量转换为字符串 调用.ReplaceAll() with "[\\D]"将所有非数字字符替换为""(无) 调用integer . parseint()抓取并从数字字符串中返回一个整数。
其他回答
有五种转换方法 第一种方法:
String str = " 123" ;
int i = Integer.parse(str);
output : 123
第二种方式:
String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123
第三种方式:
String str"123";
int i = new Integer(str);
output "123
第四种方式:
String str"123";
int i = Integer.valueOf(Str);
output "123
第五种方式:
String str"123";
int i = Integer.decode(str);
output "123
可能还有其他办法 但我现在只记得这些
使用正则表达式是做到这一点的最好方法,正如ashish sahu已经提到的那样
public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
试试这段代码,它真的工作。
int number = 0;
try {
number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
System.out.println("parse value is not valid : " + e);
}
更简单的方法是使用Integer的decode方法,例如:
int helloInt = Integer.decode(hello);
你也可以只写一行:
int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));
从执行顺序读取
使用findViewById(R.id.button1)获取视图 使用((Button)______)将视图转换为按钮 调用.GetText()从Button获取文本条目 调用.toString()将字符变量转换为字符串 调用.ReplaceAll() with "[\\D]"将所有非数字字符替换为""(无) 调用integer . parseint()抓取并从数字字符串中返回一个整数。