Displaying an error message in a Do..While loop in java -
i'm trying do..while loop display error message why re-asking user input again. code it:
do { system.out.println("\nplease enter floor on: "); current_floor = in.nextint(); } // loop until user input equal or less maximum floors while( current_floor > max_floors );{ system.out.println("please enter floor less 8"); }
the problem code "error" message i've added appears after correct user input has been entered, when need display before user input added in. ideas?
your formatting screwy, what's confusing you. ;
@ end of while
ends do-while
. braces after that, containing "error" statement, static set of braces: they're not associated loop in way.
if format code more legibly, looks this, makes clear "less 8" message placed incorrectly, , printed, once exit loop.
do { system.out.println("\nplease enter floor on: "); current_floor = in.nextint(); } while( current_floor > max_floors ); { // useless braces! system.out.println("please enter floor less 8"); } // useless braces!
if want loop until condition met while informing user of "failed" iterations, usual idiom loop forever, , break
when condition met:
while (true) { system.out.println("\nplease enter floor on: "); current_floor = in.nextint(); if (current_floor <= max_floors) { break; } // prints if user entered bad number. system.out.println("please enter floor less 8"); }
alternately, can "extract" first iteration of loop, , use conventional while
loop (or do-while
if you're committed structure reason) ensure input acceptable. personally, find previous version little cleaner, that's down personal preference , coding style.
// initial input system.out.println("\nplease enter floor on: "); current_floor = in.nextint(); // loop until input acceptable while (current_floor > max_floors) { system.out.println("please enter floor less 8"); current_floor = in.nextint(); }
as aside, it's kind of nasty referring max_floors
in code, while hard-coding magic number 8
error message: better use string formatting tell user actual maximum floor number is.
system.out.println(string.format("please enter floor less %d", max_floors+1));
as aside, naming scheme kind of weird: convention, variable names in java should use camelcase, without underscores, e.g. currentfloor
. max_floors
okay though, since seems static/enum-like variable, do conventionally use capslock underscores.
Comments
Post a Comment