Ryan
Ryan

Reputation: 57

While loops and string comparisons for my password program

I am trying to do a while loop that prints a welcome statement if password is correct and denies you if you're wrong. When you're wrong, I want it to re-ask the question. Unfortunately, when password is wrong, it just spams the end and doesn't reloop. Thanks!

import java.util.Scanner;

public class Review {
    public static void main(String[] args) {

        Scanner userInput = new Scanner(System. in );
        System.out.println("Enter user password");
        String userGuess = userInput.nextLine();
        int x = 10;

        while (x == 10) {

            if (userGuess.equals("test")) {
                System.out.println("Welcome");
                return;
            } else if (!userGuess.equals("test")) {
                System.out.println("Wrong, try again");
                break;
            }
        }
    }
}

Upvotes: 1

Views: 3685

Answers (3)

Bohemian
Bohemian

Reputation: 425178

You need the guess to be made inside the loop. And less code is good:

Scanner userInput = new Scanner(System.in);
System.out.println("Enter user password");
for (int n = 0; n < 10; n++) {
    if (userInput.nextLine().equals("test")) {
        System.out.println("Welcome");
        return;
    }
    System.out.println("Wrong, try again");
}

Usually, when you eliminate unnecessary code, clarity improves. This is such a case.

Upvotes: 0

Gyanendra Dwivedi
Gyanendra Dwivedi

Reputation: 5547

I think you are trying to create a solution, which checks 10 times for password and then exit. If so, I would recomend McGee's way to proceed forward.

Otherwise, issue with your code is that the loop will never continue after first iteration due to 'return' or 'break' encountering in the control flow.

Even though that is fixed (may be by removing any of those); the program will go into infinite loop; as the while loop will aways have a true case (x == 10).

Please let us know, what is the goal; we could help you more.

Upvotes: 1

Mark O M
Mark O M

Reputation: 1

Try this:

import java.util.Scanner;

public class Review {
    public static void main (String[]args) {

        Scanner userInput = new Scanner(System.in);

        while (true) {

            System.out.println("Enter user password");
            String userGuess = userInput.nextLine();

            if (userGuess.equals("test")) {
                System.out.println("Welcome");
                return;
            }

            else{
                System.out.println("Wrong, try again");
            }

        }
    }
}

I used while(true) instead of doing the x=10 thing that you did. And I moved the part where it asks for the password to inside the while loop. You could also move the userInput declaration to inside the loop too, if the only time you're using it is when you're asking for the password.

Upvotes: 0

Related Questions