簡體   English   中英

Integer 類型中的方法 parseInt(String) 不適用於參數(布爾值)

[英]The method parseInt(String) in the type Integer is not applicable for the arguments (boolean)

我收到錯誤Integer 類型中的方法 parseInt(String) 不適用於參數(布爾值)

這是代碼

} else if (Integer.parseInt(answerField.getText() == null)) {
                    JOptionPane.showMessageDialog(null, "You did not enter an answer!");
                }

我也試過這個,但它不起作用:

(Integer.parseInt(answerField.getText().equals("")))

&

(Integer.parseInt(answerField.getText().length()) == 0)

我只想檢查是否沒有輸入任何內容,如果是,則顯示 JOptionPane。

編輯: var answerField 是一個 JTextField,用戶在其中輸入數學問題的答案。 所以 ActionListener 然后確定答案是否正確,因此 parseInt (因為它是一個數學運算)

do {
        checkButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (Integer.parseInt(answerField.getText()) == correctAnswer) {
                    count++;
                    JOptionPane.showMessageDialog(null, "Correct");

                } else if (Integer.parseInt(answerField.getText().length()) == 0) {
                    JOptionPane.showMessageDialog(null, "You did not enter an answer!");
                } else {
                    count++;
                    JOptionPane.showMessageDialog(null, "Incorrect!");
                    System.exit(0);
                }
            }
        });
    } while (count < 11);

讓我們分析您擁有的代碼

(Integer.parseInt(answerField.getText() == null))

參數

answerField.getText() == null

返回一個布爾值,並且Integer.parseInt(bool)方法未在 Integer 類中定義。

看起來你想做:

else if (someConditionHere) {
      Integer.parseInt(answerField.getText());
      JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}

parse int 方法中的所有值都返回一個布爾值,因為它們正在執行兩個值之間的比較,結果要么是真要么是假。 您應該使用 Boolean.parseBoolean() 返回“true”或“false”字符串

Integer.parseInt(answerField.getText() == null)被評估為Integer.parseInt("someTextext" == null)然后

Integer.parseInt(true/false)

嘗試將布爾值解析為整數將導致錯誤

要檢查您的字段是否為空,請僅執行if(answerField.getText() == null)

那么如果不為空,您可以嘗試按照您的方式將字段值解析為整數。

我不確定您為什么要調用 Integer.parseInt,因為您的條件中已經有一個布爾表達式:

} else if (answerField.getText() == null) {
    JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}

請注意,如果 Java 中的條件只能接受布爾表達式,並且您不能傳入整數或任何其他您認為為的東西(例如,與 C 或 Javascript 不同)。

如果您要做的只是檢查answerField中是否包含一些字符串,那么您需要做的就是檢查它是否不為空或為空。

if(!("".equals(answerField.getText()) || null == answerField.getText()) {
    // other, non-integer-handling code here
}

如果有一個空字符串或者它是null ,您不想處理解析整數,因為這可能會導致NullPointerException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM