首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android EditText 空值導致崩潰:正確驗證與解析數值

     編輯:程式設計綜合問答

崩潰原因分析

原始碼在 Double.parseDouble(anss) 前未檢查字串是否為空或非數字,導致 NumberFormatException 或 NullPointerException。且邏輯順序錯誤:先解析再判斷空值,空值時已拋出異常。

錯誤代碼片段

anss = info.getText().toString();
double result = Double.parseDouble(anss); // 這裡直接崩潰
if (res == result) { ... }
else if (info.getText().toString().equals("")) { ... } // 永遠執行不到

正確驗證流程

  1. 先取得字串並 trim() 去除空白。
  2. 判斷 isEmpty(),為空則提示並 return。
  3. 使用 try-catch 包裹 Double.parseDouble,捕獲格式錯誤。
  4. 解析成功後再進行業務邏輯比對。

修正後的完整範例

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("請輸入有效數字");
        }
    }
});

進階建議

  • 在 XML 設定 android:inputType="numberDecimal|numberSigned" 限制鍵盤輸入。
  • 使用 TextWatcher 即時驗證,按鈕點擊時僅處理合法資料。
  • 考慮用 BigDecimal 處理金額等需精確運算的場景。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved