int [] numbers = {1,2,3,4};
Random random = new Random();
int totalGood=0;
int totalFalse=0;
String titl = "title1";
String titl2 = "Question";
String titl3 = "Error!";
boolean ages = true;
String name = JOptionPane.showInputDialog(null,"Welcome Please enter your name:",titl,JOptionPane.PLAIN_MESSAGE,new ImageIcon(image0), null,"").toString();
while(ages == true){
int age = Integer.parseInt(JOptionPane.showInputDialog(null,"Welcome" + " " + name +"!" + " " + "How old are you?",titl2,3));
if(age <=28){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:" + " " +age,titl,2));
}else if(age >=29 && age <=40){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:"+ " "+age,titl,2));
}else if(age>=41){
JOptionPane.showMessageDialog(null,String.format("Text " + " " + "Your age:" + " "+age,titl,2));
}else{
// the part where I get stuck!
// What to write here to catch an error and return the user to again input int age if he types String instead?
continue;
}
}
I'm trying to validate the user input to allow only Int and if he types a String, he will get an error and again a window for age will pop-up.
I tried everything to catch the error, but I just keep failing at this. I could not accomplish this with age=Integer.parseInt(age) or .hasNextInt or other things like this. They always give me an error.
I saw many tutorials on how to do with normal Scanner and system.println, but I cannot figure out the resolution with JOptionPane.
I tried try/catch, but I don't get it and it never works.
Can you please help me? I'm new at Java and I would appreciate any help.
EDIT: I fixed it! Thank you Andrew Vershinin so much!
while(ages == true){
Pattern AGE = Pattern.compile("[1-9][0-9]*");
String ageInput = JOptionPane.showInputDialog(null,"Welcome" + " " + name +"!" + " " + "How old are you?",titl2,3);
if(!AGE.matcher(ageInput).matches()){
JOptionPane.showMessageDialog(null,String.format("Please enter only numbers! :)"));
continue;
}
int age = Integer.parseInt(ageInput);
if(age <=28){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:" + " " +age,titl,2));
}else if(age >=29 && age <=40){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:"+ " "+age,titl,2));
}else if(age>=41){
JOptionPane.showMessageDialog(null,String.format("Text" + " " + "Your age:" + " "+age,titl,2));
}