SeanHub SeanHub - 1 month ago 8
Java Question

Stuck with looping an if statement from within itself

I am currently doing a slot machine-like project. I've ran into the problem of needing to loop an IF statement, but only if the user input is YES, within that loop? Here is some example code of what I am trying to do.

int num1 = 0;
int num2 = 0;
int num3 = 0;

Scanner scan = new Scanner(System.in);
Random numRand = new Random();

num1 = numRand.nextInt((9 - 0) + 1);
num2 = numRand.nextInt((9 - 0) + 1);
num3 = numRand.nextInt((9 - 0) + 1);

System.out.println(num1 + " " + num2 + " " + num3);

if(num1 == num2 && num1 == num3 && num2 == num3) {
System.out.println("All three match - jackpot");
System.out.printf("Would you like to play again? ");
String Yes = scan.nextLine();
if(Yes.equals("y")) {

}
String No = scan.nextLine();
if(No.equals("n")) {

}
}
else if(num1 == num2 || num2 == num3 || num1 == num3) {
System.out.println("Two number match");
System.out.printf("Would you like to play again? ");
String Yes = scan.nextLine();
if(Yes.equals("y")) {

}
String No = scan.nextLine();
if(No.equals("n")) {

}
}
else {
System.out.println("No numbers match");
}
scan.close();


From my code, you can see that within the IF statement, I am trying to run another if statement for when the user's input = Y (for yes) this is so that if the user were to enter y when prompted, then the if statement would loop.

The outcomes are stated, that if all 3 number match, then output:
if 2 numbers match, output:
if no numbers match then output:

I hope you understand

Answer

I'd suggest a do while construct.

Scanner scan = new Scanner(System.in);  
Random numRand = new Random();

boolean keep_playing = true;

do
{
    num1 = numRand.nextInt((9 - 0) + 1);
    num2 = numRand.nextInt((9 - 0) + 1);
    num3 = numRand.nextInt((9 - 0) + 1);

    System.out.println(num1 + " " + num2  + " " + num3);

    if(num1 == num2 && num1 == num3) { // && num2 == num3  - unnecessary
        System.out.println("All three match - jackpot");
    }
    else if(num1 == num2 || num2 == num3 || num1 == num3) {
        System.out.println("Two number match");
    }
    else {
        System.out.println("No numbers match");
    }

    System.out.printf("Would you like to play again? ");

    String input = scan.nextLine();
    keep_playing = input.equals("y");

} while ( keep_playing )

scan.close();