I just started to learn Java, so my program is made with the most basic codes, and I am having some problems with random numbers. I am suppose to make a program that generates a winning number, then the program itself will try to guess it. And based on the guess is high or low, the program's next guess will be limited in a new range, until it guessed the winning number, just like how humans try to guess the number. However, in the while loop, the random number guess does not update to a new random number based on the new range, and java keeps looping with the same number over and over again infinitely. At first I thought it is because I do not return the new guess value, but return will stop the while loop. I am confused, and I am trying to get some help, thank you very much!
import java.util.Random;
public class GuessNum {
public static void main(String[] args) {
int range;
range = 0;
int upper;
upper = 100;
int lower;
lower = 0;
int finaltotal;
finaltotal = 0;
for(int i = 0; i < 1000; i++) {
int total;
total = 0;
int win = (int)(Math.random() * 100 + 1);
int guess = (int)(Math.random() * 100 + 1);
while(guess != win) {
if(guess > win) {
String strGuess;
strGuess = "Your guess is: " + String.valueOf(guess);
System.out.println(strGuess);
System.out.println("Guess is high!");
upper = guess;
range = upper - lower + 1;
guess = (int)(Math.random() * range + lower);
total += 1;
}
if(guess < win) {
String strGuess;
strGuess = "Your guess is: " + String.valueOf(guess);
System.out.println(strGuess);
System.out.println("Guess is low!");
lower = guess;
range = upper - lower + 1;
guess = (int)(Math.random() * range + lower);
total += 1;
}
}
String strGuess;
strGuess = "Your guess is: " + String.valueOf(guess);
System.out.println(strGuess);
System.out.println("You win!");
total += 1;
finaltotal += total;
}
int average = finaltotal / 1000;
String strAverage;
strAverage = "The average number of guesses is: " + String.valueOf(average);
System.out.println(strAverage);
}
}
Aucun commentaire:
Enregistrer un commentaire