So, the instructions for my assignment for school are that the code takes in multiple values with a scanner, and needs to return the same message in a while loop until it breaks the while loop. Here’s my code:
public class FamilyVacation {
static final String XYZ = "yes";
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Are we there yet?");
String input = (scan.next()).toLowerCase();
while (!(input.equals(XYZ))) {
input = (scan.next()).toLowerCase();
System.out.println("Are we there yet?");
}
System.out.println("I want to go home.");
}
}
My problem is that it keeps printing an extra line of “Are we there yet”. Does anyone have any suggestions on how I can fix this?
**Edit: Here’s a screenshot of my code’s output compared to the correct output I need for this assignment:
To initialize the question to the user, so it makes sense when the code stops to get an input from the user. That way, I have an initial value for the while loop.
To initialize the question to the user, so it makes sense when the code stops to get an input from the user. That way, I have an initial value for the while loop.
Ahh, I see now, the kids initially ask “Are we there yet?” and then depending on the parent’s answer they will either keep asking the same question or demand to go home.
I haven’t dabbled in java in quite a while, but looking at the docs for Scanner, it appears that next() grabs the next “word” from the input. So I’m guessing that the line “Not yet” is triggering the while loop twice. I think maybe you want nextLine()?