2014-11-08 51 views
0

所以我在我的代碼中有一個問題,可能很容易解決,但它的第一個應用程序讓我有些鬆懈。當我在editText框中輸入任何值時,我的應用程序崩潰。我半知道爲什麼會發生,但我似乎無法解決它。Android - 在editText字段中沒有輸入時程序崩潰

public void onButtonClick(View v) { Double n1 , n2 , answer1; EditText e1 = (EditText) findViewById(R.id.num1); EditText e2 = (EditText) findViewById(R.id.num2); TextView t1 = (TextView) findViewById(R.id.answer); n1 = Double.parseDouble(e1.getText().toString()); n2 = Double.parseDouble(e2.getText().toString()); if (n1.toString().length()< 0 || n2.toString().length()< 0){ t1.setText("Please enter a number into both the base and height"); }else { answer1 = ((n1 * n2)/2); t1.setText(Double.toString(answer1)); } }

+0

'if(!e1.getText()。e quals(「」)){}'?順便說一句,不要使用e1,e2,n1,n2。使用寬度,高度等 – Simon 2014-11-08 21:42:01

+0

該聲明不起作用的應用程序仍然沒有輸入崩潰。也感謝關於命名。你的權利,我應該擺脫不良的命名習慣 – Anon 2014-11-08 21:46:11

+0

@jyoon我希望我可以downvote評論。使用try-catch檢查用戶輸入?真???? – Simon 2014-11-08 23:11:54

回答

1

如果有兩個EditText S和只有當輸入首先檢查有其轉換爲Double

if (e1.getText().length() == 0 || e2.getText().length() == 0) { 
    t1.setText("Please enter a number into both the base and height"); 
} else { 
    n1 = Double.parseDouble(e1.getText().toString()); 
    n2 = Double.parseDouble(e2.getText().toString()); 
    answer1 = ((n1 * n2)/2); 
    t1.setText(Double.toString(answer1)); 
} 

EditText.getText()不會返回null(根據源代碼),因此它是安全的使用方法(如length()

+0

謝謝!這有效並且更有意義 – Anon 2014-11-08 21:58:46

+0

很高興我能幫忙!祝你好運,不要忘記檢查這是正確的答案。 – 2014-11-08 23:14:39

1
if (!e1.getText().toString().isEmpty()) { 
    // do stuff 
} 
相關問題