我正在做一個app,有5個編輯框,1個按鈕來計算編輯框中整數的和。有的時候用戶會不在編輯框中填東西,問題就是當用戶不填東西的時候,異常就會掛起,我不知道應該怎麼做了。這個是我的代碼
try
{
if (qty1 != null)
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
else
{
qty1.setText("0");
}
if (qty2 != null)
{
int jml2 = Integer.parseInt(qty2.getText().toString());
item2 = hrg2 * jml2;
}
else
{
qty2.setText("0");
}
if (qty3 != null)
{
int jml3 = Integer.parseInt(qty3.getText().toString());
item3 = hrg3 * jml3;
}
else
{
qty3.setText("0");
}
if (qty4 != null)
{
int jml4 = Integer.parseInt(qty4.getText().toString());
item4 = hrg4 * jml4;
}
else
{
qty4.setText("0");
}
if (qty5 != null)
{
int jml5 = Integer.parseInt(qty5.getText().toString());
item5 = hrg5 * jml5;
}
else
{
qty5.setText("0");
}
int hasil = item1 + item2 + item3 + item4 + item5;
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
total.setText(String.valueOf(hasil));
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Quantity can't be empty. Please type item quantity", Toast.LENGTH_LONG).show();
}
我試過了if條件語句,但是不起作用。謝謝。
試試這個
if (qty1.getText().toString() != null && !(qty1.getText().toString().equals("")))
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}instead of,
if (qty1 != null)
{
int jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
如果你的edittext是空的話,這個條件if (qty1 != null)
會進行檢查,但是它不會檢查裡邊的數據
對於所有的edittext值都重復這個就好了。