Your formatting is all screwy, which is probably what's confusing you. The ;
at the end of your while
ends the do-while
. The braces after that, containing the "error" statement, are just a static set of braces: they're not associated with your loop in any way.
If you format your code more legibly, it looks like this, which makes it clear that your "less than 8" message is placed incorrectly, and will always be printed, once you exit the loop.
do {
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
} while( current_Floor > MAX_FLOORS );
{ // Useless braces!
System.out.println("Please enter a floor which is less than 8");
} // Useless braces!
If you want to loop until some condition is met while informing the user of "failed" iterations, the usual idiom is generally to loop forever, and then break
when your condition is met:
while (true) {
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
if (current_Floor <= MAX_FLOORS) {
break;
}
// This prints only if the user entered a bad number.
System.out.println("Please enter a floor which is less than 8");
}
Alternately, you can "extract" the first iteration of the loop, and then use a conventional while
loop (or do-while
if you're really committed to that structure for some reason) to ensure that the input is acceptable. Personally, I find the previous version a little cleaner, but that's really just down to personal preference and coding style.
// Initial input
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
// Loop until the input is acceptable
while (current_Floor > MAX_FLOORS) {
System.out.println("Please enter a floor which is less than 8");
current_Floor = in.nextInt();
}
As an aside, it's kind of nasty to be referring to MAX_FLOORS
in the code, while hard-coding the magic number 8
into your error message: it would be better to use some string formatting to tell the user what the actual maximum floor number is.
System.out.println(String.format("Please enter a floor which is less than %d", MAX_FLOORS+1));
As another aside, your naming scheme is kind of weird: by convention, most variable names in Java should use camelCase, without underscores, e.g. currentFloor
. Your MAX_FLOORS
is okay though, since it seems to be a static/enum-like variable, which do conventionally use capslock with underscores.