I'm look for some help on a bit of homework I have. I want the user to enter a numerical String, then convert it to an Integer. But I want to make a loop that will detect if the user entered in the wrong value such as "One Hundred" as apposed to "100".
What I was thinking was to do something like this:
do{
numStr = JOptionPane.showInputDialog("Please enter a year in numarical form:"
+ "\n(Ex. 1995):");
num = Integer.parseInt(numStr);
if(num!=Integer){
tryagainstr=JOptionPane.showInputDialog("Entered value is not acceptable."
+ "\nPress 1 to try again or Press 2 to exit.");
tryagain=Integer.parseInt(tryagainstr);
}
else{
*Rest of the code...*
}
}while (tryagain==1);
But I don't know how to define that "Integer" value. I essentially want it to see if it is a number or not to prevent it from crashing if the user enters the wrong thing.
Integer.parseIntmethod throwsNumberFormatExceptionif the input is not parseable as an integer. You just have to use atry/catch.