简体   繁体   中英

How do I allow another attempt at an input

So I have this code

import java.util.Scanner;
public class Test2{ 
  public void myScanner () {
    System.out.println("Do you want to have an adventure?");
    System.out.println("1 for yes, 2 for no");
    Scanner scanner = new Scanner(System.in);        
    String input = scanner.next();
    int answer = Integer.parseInt(input);
        switch (answer) {
          case 1: System.out.println("yes");
          break;

          case 2: System.out.println ("no");
          break;

          default: System.out.println("not valid answer"); 
        }
     }
 }

And what I'm trying to figure out is how to allow another attempt at answering the question after a wrong answer is given. So far, everything else works perfectly.

Just invoke myScanner() function after default: statement

 default: System.out.println("not valid answer"); 
 myScanner();

Introduce a boolean variable called validAnswer before you ask for input from the user. Give it an initial value of false .

You can then wrap the section of your code that prompts for input from the user in a while block, like so:

while(!validAnswer) {
  String input = scanner.next();
  //etc, etc.
}

You then need to modify your switch statement so that if the input is valid, set validAnswer to true in addition to printing to the console - this should let you escape from the while loop but keep the loop going if the input is invalid.

As you're learning: the basic way to do this is :

boolean exit;
    do{ 
      exit = true;
      System.out.println("Do you want to have an adventure?");
      System.out.println("1 for yes, 2 for no");
      Scanner scanner = new Scanner(System.in);    
      String input = scanner.next();
      int answer = Integer.parseInt(input);
      switch (answer) {
        case 1: System.out.println("yes");
        break;

        case 2: System.out.println ("no");
        break;

        default: System.out.println("not valid answer"); 
        exit = false;
      }   
    } while(!exit);

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