Reputation: 35
For example, I want a loop that prints out "Do you want to watch a movie?" until the user enters "yes".
Here's what I have so far:
import java.util.Scanner;
public class Testing {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
do {
System.out.println("Do you want to watch a movie?");
scan.nextLine();
String Answer = scan.next();
}
while (!Answer.equals("yes"));
Upvotes: 3
Views: 86
Reputation: 18276
the test condition is out of the scope of the { and } where you read it, so move the declaration of String answer
(lowcase) to before of the do statement so we can test it outside the block (the while instruction is out of itand is the condition to execute the block again).
And, nextLine() returns and consume the value readed, the result will be it.
String answer;
do {
System.out.println("Do you want to watch a movie?");
answer = scan.nextLine();
} while(!answer.equals("yes"));
Upvotes: 5
Reputation: 5814
You have to define the Answer
variable outside the loop scope:
Scanner scan = new Scanner(System.in);
String answer;
do {
System.out.println("Do you want to watch a movie?");
// scan.nextLine(); you don't need this
answer = scan.next();
}
while (!answer.equals("yes"));
Also use proper Java naming conventions: variable names should be lowerCamelCase.
Upvotes: 5