我的程序中2個文本框,分別是用來輸入名稱(字符串型)和數字(整型)。如果在兩個文本框都沒有輸入信息或其中的一個文本框是空的,想有一個提示框顯示“請輸入內容”或“請輸入數字”。程序總是出錯,下面是代碼片段:
public void onClick(DialogInterface dialog, int id) {
String item = itemET.getText().toString();
int quantity = Integer.parseInt(quantityET.getText().toString());
if(itemET.equals("")){
Toast t =Toast.makeText(GroceryList.this, "Please enter item", 5000);
t.show();
}
if(quantityET.equals("")){
Toast t =Toast.makeText(GroceryList.this, "Please enter quantity or enter 0 if none", 5000);
t.show();
}
這是日志中的錯誤信息:
09-19 10:01:51.766: E/AndroidRuntime(527): FATAL EXCEPTION: main
09-19 10:01:51.766: E/AndroidRuntime(527): java.lang.NumberFormatException: unable to parse '' as integer
09-19 10:01:51.766: E/AndroidRuntime(527): at java.lang.Integer.parseInt(Integer.java:362)
09-19 10:01:51.766: E/AndroidRuntime(527): at java.lang.Integer.parseInt(Integer.java:332)
09-19 10:01:51.766: E/AndroidRuntime(527): at com.mexican.recipes.GroceryList$1$1.onClick(GroceryList.java:60)
09-19 10:01:51.766: E/AndroidRuntime(527): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
09-19 10:01:51.766: E/AndroidRuntime(527): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 10:01:51.766: E/AndroidRuntime(527): at android.os.Looper.loop(Looper.java:123)
09-19 10:01:51.766: E/AndroidRuntime(527): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-19 10:01:51.766: E/AndroidRuntime(527): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 10:01:51.766: E/AndroidRuntime(527): at java.lang.reflect.Method.invoke(Method.java:507)
09-19 10:01:51.766: E/AndroidRuntime(527): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-19 10:01:51.766: E/AndroidRuntime(527): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-19 10:01:51.766: E/AndroidRuntime(527): at dalvik.system.NativeStart.main(Native Method)
請大師們幫我看看問題出現在哪裡?謝謝!
在這段代碼中有兩個獨立的問題:在一個空串中調用把字符串轉換成整型的方法會引發異常;在一個輸入框中不能對字符串進行同級比較。代碼應該這樣寫:
public void onClick(DialogInterface dialog, int id) {
String itemString = itemET.getText().toString();
String quantityString = quantityET.getText().toString();
int quantity;
if(itemString.equals(""))
{
Toast t =Toast.makeText(GroceryList.this, "Please enter item", 5000);
t.show();
}
if(quantityString.equals("")){
Toast t =Toast.makeText(GroceryList.this, "Please enter quantity or enter 0 if none", 5000);
t.show();
}
else {
quantity = Integer.parseInt(quantityString);
}
}