简体   繁体   中英

Exiting a sequence of user inputs without checking for the exit symbol ("--exit") after every input

I'm writing a program where I am taking user input to fill multiple fields in a class. I am using a scanner to get the input from the user from the command line. Since it is a command line program, I want the user to be able to write "--exit" at any point to go back to the main "menu."

Is there a way to implement this where I can avoid the repeated if-statements? It doesn't have to user a scanner to get the input. Another method is fine, as long as it takes input from the terminal.

      System.out.println("Write --exit to return to the menu\n");
      System.out.println("Enter the id: ");
      String input = scanner.next();
      if (input.equals("--exit")) {
        return;
      }
      final String id = input;

      System.out.println("Enter the description: ");
      input = scanner.next();
      if (input.equals("--exit")) {
        return;
      }
      final String description = input;

      System.out.println("Enter the price: ");
      input = scanner.next();
      if (input.equals("--exit")) {
        return;
      }
      final int price = Integer.parseInt(input);
      
      // continues below

Repeated if statements like you have now are probably the least complicated/most straightforward way to achieve the desired effect, even if they look ugly or seem like they could be refactored to avoid duplicate code.

Even if you make a single "handleUserInput" method and use it for all 3 questions, you can't put the "if(input.equals("--exit")) return;" line in there because the return statement would only exit inner method and not end the outer (AFAIK there is no way to do that). You could use something like "if(input.equals("--exit")) goBackToMenu();"instead, but that's a bad solution because it would keep increasing your stack size every time you loop through that way. Probably not an issue in most use cases but it's poor practice.

I would have the scanner throw a custom Exception with the user enters "--exit". I would also have the scanner issue the prompt and have different next() methods for the types being entered; that way your code would look like this:

public Form enterForm() throws ReturnToMenuException {
    System.out.println("Write --exit to return to the menu\n");
    final String id = scanner.nextString("Enter the id: ");
    final String desc = scanner.nextString("Enter the description: ");
    final int price = scanner.nextInt("Enter the price: "));
      .
      .
      .

  return new Form(id, desc, price...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM