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.
Try use instanceof , this method will help you with check between many types
Example
if (s instanceof String ){
// s is String
}else if(s instanceof Integer){
// s is Integer value
}
If you want just check between integer and string you can use @NKukhar code
try{
Integer.valueOf(str);
} catch (NumberFormatException e) {
//not an integer
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With