I have written this code that prompts the user to enter their month of birth and year of birth. There is some error checking: their month must be an integer and also in range from 1-12. The same for year. As it stands, I have two while loops and I can’t think of a way to combine them to still get the error message when something is wrong. I can think of it if it was just going to say “Bad input: reenter” but it needs to say what is wrong with the input. It starts with month and that month has to be good before it moves on to asking the year. If the year is wrong, it will then ask to reenter year — not go all the way back to month.
If anyone has any ideas, I’d appreciate it. The class used to check if it is an integer is one I’m required to use.
while(!monthDone) {
System.out.print("Enter Month of Birth: ");
monthInput=scan.next();
if(!(Type.isInteger(monthInput))) {
System.out.println("You need to enter an integer for month");
monthDone=false;
} else {
MOB = Integer.valueOf(monthInput);
if (MOB<1 || MOB>12) {
System.out.println("Your month is out of range");
monthDone=false;
} else {
monthDone=true;
}
while(!yearDone) {
System.out.print("Enter Year of Birth: ");
yearInput=scan.next();
if(!(Type.isInteger(yearInput))) {
System.out.println("You need to enter an integer for year");
}
else {
YOB = Integer.valueOf(yearInput);
if (YOB<1912 || YOB>2012) {
System.out.println("Your year is out of range");
yearDone=false;
}
else
yearDone=true;
}
}
}
}
} // else closed
} // Outer while close
I am just posting the while loop. When both monthDone && yearDone == true, I then go on to print how old they are, etc.
This is how I might lay it out without so much nesting.