首页 > 解决方案 > Java 猜谜游戏“可能未初始化”

问题描述

我真的需要帮助。我正在使用 BlueJ,它说“可能没有被初始化”。我如何解决它?它的正确编号大约在第 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


        }

       }
    }

}

标签: java

解决方案


我真的需要帮助。我正在使用 BlueJ,它说“可能没有被初始化”。我如何解决它?

局部作用域变量在使用前需要初始化(赋初值):

int correctNumber = 0

同样适用于您的其他变量。


推荐阅读