Question

My program asks the user: How many course have you completed? So, the users has to enter the number of courses completed on a JTextField component. My program then converts the String that has been entered in the JTextField into a Integer. When I run my program, I get a numberformatException. I tried debugging, and I noticed that my program converts the String into a Integer before the user can write anything. The program doesn't wait for the user to type anything. How can I make so my program waits for the user to enter a number before continuing to execute the code?

public class content extends JPanel implements ActionListener
{

     String number = "";
     JTextField NumtextField = new JTextField(5);

     @Override
     public void actionPerformed(ActionEvent e)
     {
         number = NumtextField.getNumtextField().getText();
     }

     int size = Integer.parseInt(number);

}
Was it helpful?

Solution

Move int size = Integer.parseInt(number); inside actionPerformed:

 public void actionPerformed(ActionEvent e){
 number = NumtextField.getNumtextField().getText();
 int size = Integer.parseInt(number);
 }

When the program starts, its trying to parse "", which is not a valid number string hence why you are getting an exception. Also maybe you should put that inside a try{}catch{} block, so in case you get an exception in real time you can handle it:

try {
 int size = Integer.parseInt(number);
}
catch (NumberFormatException e) {
System.out.println("Thats not a valid number");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top