如何将字符串转换为整数?
我有一个文本框,让用户输入一个数字:
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转换为整数?这样就跳过了中间人。如果不是,字符串到整数就可以了。
当前回答
更简单的方法是使用Integer的decode方法,例如:
int helloInt = Integer.decode(hello);
其他回答
科特林
可以使用Extension方法将它们解析为其他基本类型。
“10”toInt(。) “10”请(。) “真正的”toBoolean()。 “10 . 0”toFloat()。 “10 . 0”toDouble()。 “10”toByte(。) “10”toShort(。)
Java
String num = "10";
Integer.parseInt(num );
请参阅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);
}
您可以使用以下方法将字符串解析为整数:
int value = Integer.parseInt (textView.getText () .toString ());
(1)输入:12然后它将工作..因为textview已经把这个12数字作为“12”字符串。
(2)输入:"abdul",那么它将抛出一个异常,即NumberFormatException。 所以为了解决这个问题,我们需要使用try catch,就像我下面提到的:
int tax_amount=20;
EditText edit=(EditText)findViewById(R.id.editText1);
try
{
int value=Integer.parseInt(edit.getText().toString());
value=value+tax_amount;
edit.setText(String.valueOf(value));// to convert integer to string
}catch(NumberFormatException ee){
Log.e(ee.toString());
}
你也可以参考以下链接了解更多信息: http://developer.android.com/reference/java/lang/Integer.html
试试这段代码,它真的工作。
int number = 0;
try {
number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
System.out.println("parse value is not valid : " + e);
}
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());