// 錯誤 1: R.id.editText1 是資源 ID (int),非用戶輸入文本
final String str = String.valueOf(R.id.editText1);
// 錯誤 2: 未獲取 EditText 實例調用 getText()
// 錯誤 3: setText(int) 會被識別為資源 ID,需轉字符串
ET2.setText(z);
findViewById 獲取 EditText 實例。getText().toString() 獲取用戶輸入字符串。Integer.parseInt() 或 Integer.valueOf() 轉為索引。setText(String.valueOf(value)) 設置結果文本。
public class MainActivity extends AppCompatActivity {
private EditText etIndex, etResult;
private Button btnCalc;
private final int[] oil = {20, 30, 40, 50, 60, 70, 80, 90, 100};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etIndex = findViewById(R.id.editText1);
etResult = findViewById(R.id.editText2);
btnCalc = findViewById(R.id.button1);
btnCalc.setOnClickListener(v -> {
String input = etIndex.getText().toString().trim();
if (input.isEmpty()) {
Toast.makeText(this, "請輸入索引", Toast.LENGTH_SHORT).show();
return;
}
try {
int index = Integer.parseInt(input);
if (index < 0 || index >= oil.length) {
Toast.makeText(this, "索引超出範圍 0-" + (oil.length-1), Toast.LENGTH_SHORT).show();
return;
}
int value = oil[index];
etResult.setText(String.valueOf(value)); // 必須轉字符串
} catch (NumberFormatException e) {
Toast.makeText(this, "請輸入有效整數", Toast.LENGTH_SHORT).show();
}
});
}
}
| 錯誤寫法 | 正確寫法 | 說明 |
|---|---|---|
String.valueOf(R.id.editText1) | editText.getText().toString() | 資源 ID ≠ 用戶輸入 |
et.setText(intValue) | et.setText(String.valueOf(intValue)) | int 版本視為資源 ID |
| 無越界檢查 | if (index < 0 || index >= arr.length) | 防止 ArrayIndexOutOfBoundsException |
| 無格式異常捕獲 | try-catch NumberFormatException | 用戶輸入非數字時不崩潰 |
inputType="number" 彈出數字鍵盤。focusable="false" 禁止編輯,或用 TextView 更合適。核心修正:**獲取 EditText 實例 → 讀取文本 → 解析整數 → 越界檢查 → 設置字符串結果**。養成防禦性編程習慣:輸入驗證、異常捕獲、邊界檢查、類型轉換正確。