The code I am trying to execute records guesses from numbers 1 to 100 using .randomNextInt(100) + 1. It is meant to do so only until the chosen number has been generated. Then, a message with the number of tries it took to generate is created.
This is my current code:
import java.util.*;
import java.util.Random;
public class FeelingLucky {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random(1);
final int theNumber = random.nextInt(100) + 1;
int Tries = 1;
System.out.print("Pick a number between 1 and 100: ");
int theGuess = scanner.nextInt();
while (theGuess != theNumber) {
theGuess = random.nextInt(100) + 1;
System.out.println(theGuess);
Tries++;
if (theGuess == theNumber)
break;
}
System.out.println("It took " + Tries + " tries to match");
}
}
I tried using the if and break statment after Tries++ to see if that would make it stop at the chosen number, however it did not seem to do anything. Help would be appreciated, thank you.
Update: I was able to get it. I had the "guess" and the chosen "number" switched around. I thought you were supposed to create the chosen number yourself but you were supposed to read it in from the output given in the assignment.
import java.util.*;
import java.util.Random;
public class FeelingLucky {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random(1);
int theGuess = 0;
System.out.print("Pick a number between 1 and 100: ");
final int theNumber = scanner.nextInt();
int Tries = 0;
while (theGuess != theNumber) {
theGuess= random.nextInt(100) + 1;
System.out.println(theGuess);
Tries++;
}
System.out.println("It took " + Tries + " tries to match");
}
}