Random Number Guesser Game
Write a program where a random number is generated. Then the user tries to guess the number. If they guess too high display something to let them know, and same for if they guess a number that is too low. The loop must iterate until the number is guessed correctly.
import java.util.Random;
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
{
// stores actual and guess number
int answer, guess;
// maximum value is 100
final int MAX = 100;
// takes input using scanner
Scanner in = new Scanner(System.in);
// Random instance
Random rand = new Random();
boolean correct = false;
// correct answer
answer = rand.nextInt(MAX) + 1;
// loop until the guess is correct
while (!correct) {
System.out.println(
"Guess a number between 1 and 100: ");
// guess value
guess = in.nextInt();
// if guess is greater than actual
if (guess > answer) {
System.out.println("Too high, try again");
}
// if guess is less than actual
else if (guess < answer) {
System.out.println("Too low, try again");
}
// guess is equal to actual value
else {
System.out.println(
"Yes, you guessed the number.");
correct = true;
}
}
System.exit(0);
}
}
import java.util.Scanner
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextInt());
Random n = newRandom();
int newNumber;
int oldNumber = -1; //Will never be matching the random number.
for(int i=0;i<100;i++){
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextInt());
do{
newNumber = n.nextInt(100);
} while (newNumber == oldNumber);
System.out.println(newNumber);
oldNumber = newNumber;
}