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".
You could try a try-catch block. Your input has to be a number. So you could do
If you don't want to do the method again, it may be an option to write