我真的需要帮助。我使用BlueJ,它说“可能没有初始化”。我如何解决它?它的 correctNumber 大致是16行。
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Random randomNumber = new Random();
int correctNumber;
int guessTracker;
int guessLimit = 6; //the number of tries
int userInput;
Scanner in = new Scanner(System.in);
int game = 1;
boolean winTracker = false;
while (1 == game)
correctNumber = randomNumber.nextInt(1100); //computer generates a random number, max 100
userInput = 0;
guessTracker = 0;
System.out.println("Hello and welcome to this number guessing game. Please guess the number between 1 and 100 and I will help you by telling you if your guess is too high or low: ");
while (**correctNumber** != userInput && guessTracker < guessLimit){
userInput = in.nextInt();
guessTracker++;
if (userInput == correctNumber){
System.out.println("You have won the game! Your reward is a fact game: Did you know the first working camera was invented in 1816! "); //winner message, with a unlocked fact game
System.out.println("The correct number was " + correctNumber); //the correct number
System.out.println("It took a total of " + guessTracker + " guesses"); //number of guesses it took the user to guess the right number.
}
else if (userInput < correctNumber){
System.out.println("Your number is too low"); //displays that the users guess is too low
System.out.println("Please enter your next guess: "); //// user can now eneter their next guess
}
else if (userInput > correctNumber){
System.out.println("Your number is too high"); //displays that the users guess is too high
System.out.println("Please enter your next guess: "); // user can now eneter their next guess
}
if (correctNumber != userInput){
System.out.println("Sorry you have run out of guesses! The correct number was: " + correctNumber); // displays the correct number
}
}
}
}
答案 0 :(得分:0)
我真的需要帮助。我使用BlueJ,它说“可能没有初始化”。我该如何解决?
本地范围变量需要在使用前初始化(分配初始值):
int correctNumber = 0
同样适用于您的其他变量。
答案 1 :(得分:0)
您需要将correctNumber初始化为一个值。
情况并非总是如此,但想一想:
你调用while(1 == game)
然后将correctNumber初始化为一个随机数,correctNumber = randomNumber.nextInt(1100)
这会初始化correctNumber,但是当java编译器编译你的应用程序时,它不能确定1 == game
是真正。因此,当编译器到达下一个循环while (**correctNumber** != userInput && guessTracker < guessLimit)
时,您的编译器会发现correctNumber尚未初始化,即使它是第一个循环。
简而言之,编译器不知道是否会输入循环,因此user3437460在说你需要初始化局部范围变量时是绝对正确的,在这种情况下int correctNumber = 0
将完美适合你。