原始碼在 Double.parseDouble(anss) 前未檢查字串是否為空或非數字,導致 NumberFormatException 或 NullPointerException。且邏輯順序錯誤:先解析再判斷空值,空值時已拋出異常。
anss = info.getText().toString();
double result = Double.parseDouble(anss); // 這裡直接崩潰
if (res == result) { ... }
else if (info.getText().toString().equals("")) { ... } // 永遠執行不到
trim() 去除空白。isEmpty(),為空則提示並 return。try-catch 包裹 Double.parseDouble,捕獲格式錯誤。buttonHash.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText info = findViewById(R.id.entry);
TextView msg = findViewById(R.id.tell);
String input = info.getText().toString().trim();
if (input.isEmpty()) {
msg.setText("Empty!");
return;
}
try {
double userVal = Double.parseDouble(input);
if (res == userVal) {
msg.setText("Correct");
} else {
msg.setText("Incorrect");
}
} catch (NumberFormatException e) {
msg.setText("請輸入有效數字");
}
}
});
android:inputType="numberDecimal|numberSigned" 限制鍵盤輸入。TextWatcher 即時驗證,按鈕點擊時僅處理合法資料。BigDecimal 處理金額等需精確運算的場景。