How can I only accept numbers as a valid input on JOptionPane?

193 Views Asked by At

I'm making a simple program in Java that tries to calculate the ideal weight based on your gender, but in the part that asks for the height I need the JOptionPane to only accept numerical values as input.

public class IdealWeightCalculator {

    public static void main(String[] args) {
        
         String gender= "";
         
         do {
             
             gender= JOptionPane.showInputDialog("Enter your gender (M/F)");

         } while(gender.equalsIgnoreCase("M") == false && gender.equalsIgnoreCase("F") == false);
         
        
         int height= Integer.parseInt(JOptionPane.showInputDialog("Enter your height in centimeters."));
         

         int idealWeight = 0;
         
         if (gender.equalsIgnoreCase("M")) {
             
             idealWeight = height - 110;
             
         }
         
         else if(gender.equalsIgnoreCase("F")) {
             
             idealWeight = height - 120;
             
         }
         
         System.out.println("Your ideal weight is " + idealWeight + " units of love.");
         
    }

}

When I put a string instead of a number the program throws an exception and stops working.

I tried implementing the solution with this code:

while (!height.hasNextInt()) {
                
    System.out.println("Enter a number, please.");
                
    height.nextLine();
                
}

But it throws this error: "Cannot invoke hasNextInt() on the primitive type int".

3

There are 3 best solutions below

0
Zero On

You could try a try-catch block. Your input has to be a number. So you could do

int height;
try
{
    height= Integer.parseInt(JOptionPane.showInputDialog("Enter your height in centimeters."));
}
catch(Exception e) // or InputMismatchException, that's what I used
{
    main(null); // start over if there is an invalid input
}

If you don't want to do the method again, it may be an option to write

int height;
boolean valid = false;
while(valid==false)
{
    valid = true;
    try
    {
        height= Integer.parseInt(JOptionPane.showInputDialog("Enter your height in centimeters."));
    }
    catch(Exception e) // or InputMismatchException
    {
        valid = false;
    }
}
0
SandroFlex On

I solved the problem by using a different approach:

        String input = JOptionPane.showInputDialog("Enter your height in centimeters:");
    while (!input.matches("\\d+")) {
        input = JOptionPane.showInputDialog("Please enter a valid number:");
    }
    height = Integer.parseInt(input);

THANKS!!

0
g00se On

Why not make it impossible to enter anything other than a number?

Integer[] heights = IntStream.range(100, 250).boxed().toArray(Integer[]::new);
Integer height = (Integer)JOptionPane.showInputDialog(
            null,
            "Please enter your height in centimeters",
            "Ideal Weight Calculator",
            JOptionPane.PLAIN_MESSAGE,
            null,
            heights,
            null);
System.out.printf("You chose height of %s%n", height);