I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string
. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('')
to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score ;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText
is completely clear?
CodePudding user response:
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string
. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score ;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
CodePudding user response:
The variable userAnswer
doesn't get cleared when answerText
is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer);
is called at a point where userAnswer
is empty (because it can't make a number out of nothing).