第一个Java程序:java.lang.NumberFormatException:对于输入字符串:" "



我正在Java编写我的第一个程序。我处于7年级。我无法弄清楚为什么我的"猜测按钮"不起作用。我的调试器说

" awt-esventqueue-0" java.lang.numberformatexception

我的输入字符串是""

public class GuessingGame extends JFrame
{
    private JTextField txtGuess;   // text field for the user's guess
    private int theNumber;             //the number we're trying to guess
    private JTextField textField;
    public void checkGuess() {  // method/function to check too high or too low
            // get the user's guess
            String guessText = txtGuess.getText();
            String message = "";    
            // check the user's guess for too low/too high
            int guess = Integer.parseInt(guessText);
            // too high 
            if (guess > theNumber)
            {
                message = guess + " was too high. Guess again!";
                lblOutput.setText(message);
            }
            // too low
            else if (guess < theNumber)
            {
                message = guess + " was too low. Guess again!";
                lblOutput.setText(message);
            }
            else 
            {
                 message = guess + " was right! You win! Let's play again! ";
                 lblOutput.setText(message);
                 newGame();
            }
    }
         public void newGame(){  // create a new random number  1..100
            theNumber = (int)(Math.random() * 100 + 1); 
         }
         public GuessingGame() {
         getContentPane().setLayout(null);
        ...
        txtGuess = new JTextField();
        panel.add(txtGuess);
        txtGuess.setColumns(10);
        textField = new JTextField();
        textField.setBounds(366, 18, 71, 22);
        panel.add(textField);
        textField.setColumns(10);
        JButton btnGuess = new JButton("Guess!");
        btnGuess.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                checkGuess();
            }
        });
        btnGuess.setBounds(195, 159, 97, 25);
        ...
    }
...

我不知道是什么原因导致错误。

我不建议您的代码。您应该切换案例或设计模式。

解决方法:

        public void checkGuess() {  // method/function to check too high or too low
        // get the user's guess
        String guessText = txtGuess.getText();
        String message = "";   
        if(guessText.isEmpty()){
           return;
        }
        ...

从您提供的代码中,我唯一能得到的结论是您不检查变量"猜测"。

在integer.parseint(String s(方法中,字符串中的字符必须全部为十进制数字。@source docs.oracle

so:

if ( !guessText.isEmpty()){
  rest of the code
} else {
message = "The guess cannot be empty :(";
lblOutput.setText(message);
}

希望这有所帮助。如果这不起作用。我将需要更多输入代码。

最新更新