I am trying to create a simple number guessing GUI game. I am using 'Integer.parseInt' to get the user's input as an integer instead of string so it can be compared. The program still executes as expected but it gives me the following error in the console:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:678)
at java.base/java.lang.Integer.parseInt(Integer.java:784)
at Window.takeGuess(Window.java:58)
at Window$2.actionPerformed(Window.java:32)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
line 58 is where the Integer.parseInt command is used and line 32 is where the takeGuess() function is called. My code is shown below:
public void takeGuess() {
while (playing) {
// retrieve input and convert to integer for comparison
int guess = Integer.parseInt(txtGuess.getText());
txtGuess.setText(null);
// decide outcome of guess
if (guess > number) {
txtDescription.setText("Too high!");
} else if (guess < number) {
txtDescription.setText("Too low!");
} else {
win = true;
txtDescription.setText("You win!");
playing = false;
}
// increment guess counter then repeat if needed
guessCount++;
currentScore.setText("" + guessCount);
System.out.println("received guess\n");
}
}
I originally had txtGuess.setText(null)
set to txtGuess.setText("")
and it gave the same error. As I said, the program still functions despite this error but I'd obviously like to get it fixed anyway. Can anyone help?
This comment helped solve the problem:
I introduced a new boolean called 'lose' which is set to true if they give up. Also changed the while loop to an if statement so function only does something when both win = false and lose = false, i.e. they're still playing.
It no longer loops back around to be met with an empty string to be parsed, which gave the error.