Guessing Game Without Loops

Viewed 50

I am attempting to make a guessing game but the key is that I cannot use loops: I've written my code however the code stops at the first iteration of the if-else statement. Is there a way to make it continue three times? Would a switch statement work better in this case?

import java.util.Scanner;


public class TestProgram {

public static void main(String args[])
{
    
    int random = (int) (Math.random() * 10);
    int answer;
    int count = 0;
    int maxGuess = 3;
    
    
    Scanner keyboard = new Scanner(System.in);
    
    System.out.println("Welcome to the game of guess it.");
    System.out.println("I will choose a number between 0 and 9");
    System.out.println("You will try to guess that number. If you guess wrong, I will tell you if you guessed too high or too low.");
    System.out.println("Okay, I'm thinking of a number. Try to guess it.");

    
        answer = keyboard.nextInt();
    
    if (maxGuess > count) 
    {
        
    
        if (random == answer)
        {
            System.out.print("You're correct!");
            
        }
        else if (answer > random)
        {
            System.out.println("Your number is lower than " + answer + ". Try again."); 
        
        }
        else if (answer < random)
        {
            System.out.println("Your number is higher than " + answer + ". Try again.");
        }
    
        count++;
    
    }
    else if (maxGuess == count)
    {
        System.out.println("You are out of turns.");
        System.out.println("The number was " + random + ".");
    }
    
}
}
0 Answers
Related