我真正坚持的是倒数第二个变量 userGuessDifference。它保持为零,使我的第二个 while 循环无法正常运行,因为它只是不断返回到第一个 else if 语句。
public class GuessingGame {
/**
* @param args
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
int userGuessDifference = (Math.abs(correctAnswer) - Math.abs(userGuess));
boolean flag = false;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10)
{
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
}
else if (difficulty == 25)
{
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
}
else if (difficulty == 50)
{
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
}
else
{
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (!flag || (counter <= guesses))
{
if (userGuess == correctAnswer)
{
System.out.println("CONGRATS YOU WIN!");
flag = true;
}
else if ((userGuessDifference <= (difficulty * .10)))
{
System.out.println("HOT!");
userGuess = keyboard.nextInt();
counter++;
}
else if ((userGuessDifference < (difficulty * .25)) && (userGuessDifference > (difficulty * .10)))
{
System.out.println("Warm...");
userGuess = keyboard.nextInt();
counter++;
}
else
{
System.out.println("Ice cold.");
userGuess = keyboard.nextInt();
counter++;
}
}
}
}