/*Do method to continually ask for correct spelled day until it matches a valid input */
do {
System.out.print('\n' + "What is the current Day (Monday-Sunday): ");
currentDay = stdIn.nextLine();
}while (!(currentDay.equals("Sunday") || currentDay.equals("Monday") ||
currentDay.equals("Tuesday") || currentDay.equals("Wednesday") ||
currentDay.equals("Thursday") || currentDay.equals("Friday") ||
currentDay.equals("Saturday")));
if(!currentDay.equals(dayOfFlight)){
System.out.println("Today isn't your day for a flight, keep cheching");
}
while (!currentDay.equals(dayOfFlight));
System.out.print("What is the current hour (Military time): ");
int currentHour = stdIn.nextInt();
int time = (hourOfFlight - currentHour);
System.out.println('\n' + "You have " + time + " hours to go.");
Program will not loop back until correct
55 views Asked by Chris At
3
There are 3 answers
0
On
Scanner reader = new Scanner(System.in);
String currentDay,dayOfFlight="Monday";
int hourOfFlight=10;
do {
System.out.print('\n' + "What is the current Day (Monday-Sunday): ");
currentDay = reader.nextLine();
if(!currentDay.equals(dayOfFlight)){
System.out.println("Today isn't your day for a flight, keep cheching");
}
}
while (!currentDay.equals(dayOfFlight));
System.out.print("What is the current hour (Military time): ");
int currentHour = reader.nextInt();
int time = (hourOfFlight - currentHour);
System.out.println('\n' + "You have " + time + " hours to go.");
You doesn't need to use that while loop to check until correct. (if that is what you are trying to achieve.)
1
On
Your second while
will either do nothing or loop infinitely.
To check this you can step through the code in your debugger.
while (!currentDay.equals(dayOfFlight));
is the same as
while (!currentDay.equals(dayOfFlight)) {
// nothing changes so loop forever
}
What you may have intended is to have a second do/while
loop where this is the end.
Look at your second
while
:It is like Peter Lawyrey said, "you may have intended to have a second do/while loop where this is the end". The beginning of this second do/while is most likely outside of the first, thus encapsulating the first and executing it until
currentDay.equals(dayOfFlight)
returns true:On a side note, you might want to change
currentDay#equals
tocurrentDay#equalsIgnoreCase
andSystem#print
toSystem#println
.