Skip to content
Advertisement

JAVA Do/while loop not returning the value

I’m new at stackoverflow and coding. I’m trying to make a method for validating the user input. The user is only allowed to answer, add, show or exit. But I keep getting stuck in the first while loop. I tried to change it to !userChoice.equals.. but it is not working. What am I doing wrong.

 public static String userFunction() {
        Scanner sc = new Scanner(System.in);
        String userChoice = "test";
        do {
            userChoice = sc.next().toLowerCase();
            while (userChoice.equals("add") || userChoice.equals("exit") || userChoice.equals("show")) {
                System.out.println("Please fill in add, show or exit");
                userChoice = sc.next().toLowerCase();
            }
            while (!userChoice.equals("add") || !userChoice.equals("show") || !userChoice.equals("exit")) ;
            return userChoice;
        } while (userChoice == "test");
    }

Answer

Your posted code has three loops – two “while” loops, and an outer “do” loop. It isn’t necessary to use more than one loop.

Taking a step back, you are describing a method that should:

  • accept user input
  • check if the input is “allowed” or not – must be one of “add”, “show”, or “exit”
  • if input is one of those three, return it to the caller
  • if input is not one of those three, show a message to the user and prompt again
  • do this forever until the user enters valid input

Here’s a method which does those things:

public static String getInput() {
    Scanner scanner = new Scanner(System.in);
    String input;
    while (true) {
        input = scanner.next().toLowerCase();
        if (input.equals("add") || input.equals("show") || input.equals("exit")) {
            return input;
        } else {
            System.out.println("Unsupported input: [" + input + "], enter: add, show, or exit");
        }
    }
}

And here’s a sample run + output:

String input = getInput();
System.out.println("from getInput(): " + input);

adf
Unsupported input: [adf], enter: add, show, or exit
show
from getInput(): show
Advertisement