When typing incorrectly sequentially, the loop breaks java

When you enter a random value such as "i" twice in a row, the program ends. I would like to see "Invalid data, please try again" and then "Do you want to play again", keep repeating until neither N nor Y is entered.

7 8 5
No numbers match
Do you want to play again?
i
Invalid data please try again
Do you want to play again?
i
Thank you for using this program

      

It should be:

7 8 5
No numbers match
Do you want to play again?
i
Invalid data please try again
Do you want to play again?
i
Invalid data please try again
Do you want to play again?

      

... etc.

Code:

import java.util.Random;
import java.util.Scanner;

public class TestSlotMachine {

    public static void main(String[] args) {
        String choice;

        Scanner keyboardScanner = new Scanner(System.in);

        do {
            Random randomNumber = new Random();
            int slot1, slot2, slot3;

            slot1 = randomNumber.nextInt(9);
            slot2 = randomNumber.nextInt(9);
            slot3 = randomNumber.nextInt(9);

            System.out.println(slot1+" "+slot2+" "+ slot3);

            if (slot1 != slot2 && slot1 != slot3 && slot2 != slot3) {
                System.out.println("No numbers match");
            }
            else if (slot1 == slot2 && slot2 == slot3) {
                System.out.println("Three numbers match");
            }
            else {
                System.out.println("Two numbers match");
            }

            System.out.println("Do you want to play again?");
            choice = keyboardScanner.next();
            if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")) {
                System.out.println("Invalid data please try again");
                System.out.println("Do you want to play again?");
                choice = keyboardScanner.next();
            }

        } while (choice.equalsIgnoreCase("y"));

        System.out.println("Thank you for using this program");
        keyboardScanner.close();
    }
}

      

+3


source to share


1 answer


if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

can be



while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

+1


source







All Articles