-1

How to escape while loop by typing a certain string ( words ). Basically I'm trying to create a program that operates similar to a computer login process and the loop asks to enter name and password. However if I want to exit the loop I type a certain word which allows me to exit the loop. If that specific word isn't type then the loop continues

Tried using != Operator but doesn't work

1 Answers1

0

You could consider using the Scanner class.

Essentially use it's nextLine method to capture the input data each time.

Once you done with the actions in your logic, break out of it if user enters the word you looking for. Else repeat and rinse.

Example:

public void validate() {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.print("Enter username: ");
        String username = scanner.nextLine();
        System.out.print("Enter password: ");
        String password = scanner.nextLine();
        System.out.println("Username: " + username + ", Password: " + password);
        System.out.println("Type 'cancel' to exit or any other key to continue");
        String input = scanner.nextLine();
        if (input.equalsIgnoreCase("cancel")) {
            break; // exit loop if input is "cancel"
        }
    }
}
kar
  • 4,791
  • 12
  • 49
  • 74