简体   繁体   中英

java - Exception in thread “main” java.lang.NumberFormatException: For input string: “” at

I am trying to run the below example whereby if I enter a letter in an integer box/field or select Ok/Cancel without entering a value that it then exits ok or forces you to enter a valid numeric value.

For the text fields it works fine but not for the integer, I get the below error.

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)

 for this code,  is it possible to achieve what I want?  thanks for any answers in advance




import javax.swing.*;



   public class Methods
   {
    public static void main(String[] args)



    {  

        //THIS IS FOR THE 1ST POP UP BOX
        // prompt the user to enter their name
        String name = JOptionPane.showInputDialog( "What is your Firstname?");

        // get the user's input. note that if they press Cancel, 'name' will be 
        null
        System.out.printf("The user's name is '%s'.\n", name);

//

        //THIS IS FOR THE 2ND POP UP BOX
        // prompt the user to enter their name
        String nametwo = JOptionPane.showInputDialog(frametwo, "What is your 
       Surname?");

        // get the user's input. note that if they press Cancel, 'name' will be 
      null
        System.out.printf("The user's name is '%s'.\n", nametwo);

//

        //THIS IS FOR THE 3RD POP UP BOX
        // prompt the user to enter their age
        int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree, 
      "How old are you?"));
        //if (num.isEmpty())

        // get the user's input. note that if they press Cancel, 'age' will be 
       null
        System.out.printf("Your age is '%s'.\n", namethree);


        System.out.println("********************************");

        System.exit(0);
    }


    }

You need to add exception handling around the call to Integer.parseInt to catch the conversion error - this method will throw a NumberFormatException for any string that can't be converted into an Integer.

Something like:

try
{
    int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree,
        "How old are you?"));
}
catch (NumberFormatException)
{
    //TODO: display an error message and retry the input
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM