Random number game (java programming)?

AngeloS

New member
How would I loop this so that the user can keep guessing numbers?

import java.util.Scanner;
import java.util.Random;
public class random

{
public static void main (String[]args)
{
int answer;
int number;
int count;
count=0;

Scanner reader= new Scanner(System.in);
Random generator = new Random();
answer= (generator.nextInt(100));

System.out.print("Guess the number:");
number = reader.nextInt();

if (answer==number)
{
System.out.println("Great! You guessed it in" + count + "guesses");
count++;
}
else if (answer>number)
{

System.out.println("That is too low. Try Again.");
count++;

}

else

{
System.out.println("That is too high. Try Again");
}

}
}
 
while(correct = false)
(
System.out.print("Guess the number:");
number = reader.nextInt();
count++;

if (answer==number)
{
correct = true;
System.out.println("Great! You guessed it in" + count + "guesses");
}
else if (answer>number)
{

System.out.println("That is too low. Try Again.");


}

else

{
System.out.println("That is too high. Try Again");
}
)
 
I would do it differently.

public static void main(String[] args)
{
int answer = 0;
int again = 1;
int count = 0;
Scanner input = new Scanner(System.in);
while (again == 1) // Start game loop
{
Random generator = new Random();
int theNum = generator.nextInt(100);

while (answer != theNum) // Current game loop
{
System.out.print("Guess the number: ");
answer = input.nextInt();
count++;

if(answer > theNum)
System.out.println("Lower!");
else if (answer < theNum)
System.out.println("Higher!");
else
{
System.out.println("You guessed the number in " + count + " attempts!");
count = 0;
System.out.println("Would you like to play again (1 = yes 2 = no): ");
again = input.nextInt();
}
}
}
}
 
Back
Top