問題描述
如何將字符串轉(zhuǎn)換為整數(shù)?
How do I convert a string into an integer?
我有一個文本框讓用戶輸入一個數(shù)字:
I have a textbox I have the user enter a number into:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
并將值賦給字符串hello
.
我想把它轉(zhuǎn)換成一個整數(shù),這樣我就可以得到他們輸入的數(shù)字;稍后將在代碼中使用.
I want to convert it to a integer so I can get the number they typed; it will be used later on in code.
有沒有辦法讓 EditText
變成一個整數(shù)?那將跳過中間人.如果沒有,字符串轉(zhuǎn)整數(shù)就可以了.
Is there a way to get the EditText
to a integer? That would skip the middle man. If not, string to integer will be just fine.
推薦答案
查看 Integer 類和靜態(tài) parseInt()
方法:
See the Integer class and the static parseInt()
method:
http://developer.android.com/reference/java/lang/整數(shù).html
Integer.parseInt(et.getText().toString());
您需要捕獲 NumberFormatException
以防在解析時出現(xiàn)問題,因此:
You will need to catch NumberFormatException
though in case of problems whilst parsing, so:
int myNum = 0;
try {
myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
這篇關(guān)于在Android上將字符串轉(zhuǎn)換為整數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!