loop while with string

Viewed 67

I want to make a loop where every time I write in "no" it will repeat the loop and ask him once more if he wants to create an account

System.out.println("you want to create a account?");
Scanner account = new Scanner(System.in);
String account1 = account.nextLine();

while (!account1.equals("no")) {
    String account = account.nextLine();
}
2 Answers

Your variable names are confusing and make your code hard to understand and debug, and the code won't even compile as given, producing:

$ javac Test.java
Test.java:13: error: variable account is already defined in method main(String...)
            String account = account.nextLine();
                   ^
Test.java:13: error: cannot find symbol
            String account = account.nextLine();
                                    ^
  symbol:   method nextLine()
  location: variable account of type String
2 errors

This error is because you are declaring a second (String) variable that is also named "account" which shadows the Scanner variable named account.

If I rename these variables it becomes much clearer — the Scanner is where you are getting your input, so I rename this as Scanner input and when you ask about creating an account you are not getting an account, you are getting an answer to the question, so I rename this as String answer.

Initializing answer to be "no" makes the while loop easier (though IRL I wouldn't initialize it, I would use a do...while)

This gives me the result ...

import java.util.Scanner;

public class Test
{
    public static void main(String...args)
    {
        Scanner input = new Scanner(System.in);
        String answer = "no";

        while (answer.equalsIgnoreCase("no")) {
            System.out.println("Do you want to create an account?");
            answer = input.nextLine();
        }
    }
}

You can use:

System.out.println("you want to create a account?");
Scanner scanner = new Scanner(System.in);
String account = "no";

while (account.equals("no")) {
account = scanner.nextLine();
}
Related