Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When entering erroneous consecutively, loop breaks java

Tags:

java

When you enter a random value such a 'i' two times in a row, the program terminates. I would like it so the "Invalid data please try again" followed by "Do you want to play again" keep repeating until either an N or a 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?

... and so on.

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();
    }
}
like image 638
Adam Avatar asked Sep 06 '26 14:09

Adam


1 Answers

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

can become

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

like image 78
Michael Laffargue Avatar answered Sep 08 '26 03:09

Michael Laffargue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!