samedi 18 février 2017

How to get a scanner to revert back to first set of if/else statements in java?

I have this scanner that works for the two if statements but when it comes to the else statement (if i input random letters it prompts the user with 'please input yes or no') if i input "Yes" it is supposed to run the method real, but instead it just ends the program. How do i get it to take the user input "yes" and then run the method that corresponds with "yes" in the first if statement? i added the for loop to try and fix this problem, and it did, but it also changed the rest of my code to run the real method twice, which is not what i wanted.

  public static void scanner() {
    System.out.println("Is this a real scenario? Please enter 'Yes' or 'No'.");
    Scanner scan = new Scanner(System.in);
    String answer;
    answer = scan.nextLine();
    //for (int x = 0; x < 2; x++ ) {
        if (answer.equals("Yes") || answer.equals("yes")) {
            real();
        } else if (answer.equals("No") || answer.equals("no")) {
            hypothetical();
        } else {
            System.out.println("Please enter 'Yes' or 'No'.");
            answer = scan.nextLine();
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire