嘿伙计们,我相信这里有一些显而易见的东西,我只是没有看到。当我在GuessingGame3构造函数中设置game.max值时,我需要一些帮助来试图弄清楚为什么我得到一个空指针异常。似乎无论我做什么,价值都不会被设定。即使我明确设置了值,它仍然会引发错误。我已经尝试将max变量更改为静态,但也没有用。很多人都说你需要初始化我所做的价值并且没有用。请帮忙。
package guessinggame3;
import java.util.Random; //provides methods that return a random integer in
//the range 0 to 4294967296.
import java.util.Scanner; //enable the user to input values from the keyboard
public class GuessingGame3
{
public int max;
public int answer;
public int maxGuessesAllowed;
public int numGuessTaken;
public static int currentGuess;
public static int previousGuess;
public boolean gameOver;
public int differential;
public GuessingGame3 game;
public static void main(String[] args)
{
GuessingGame3 game = new GuessingGame3();
game.GuessingGame3();
}
public void GuessingGame3()
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Guessing Game.");
System.out.println("Enter the maximum number:");
game.max = sc.nextInt(); // input maximun number of guesses
Random generator; // New random number generator
generator = new Random();
game.answer = generator.nextInt(game.max); // the randomly chosen answer
System.out.println("Enter the maximum number of guesses allowed:");
maxGuessesAllowed = sc.nextInt();
game.newGame(maxGuessesAllowed);
}
public void newGame(int GuessesAllowed) // Given the max,generate answer
{
game.maxGuessesAllowed = GuessesAllowed;
Random generator = new Random(); // New random number generator
int answer = generator.nextInt(max); // the randomly chosen answer
System.out.println("The answer is:" + answer);
game.gameOver = false;
game.differential = game.max;
game.numGuessTaken = 0;
game.guess();
}
public void guess()
{
/* Takes in int answer & returns string response */
Scanner sc = new Scanner(System.in);
while(!gameOver)
{
System.out.println("Enter your guess:");
currentGuess = sc.nextInt();
if(answer == currentGuess) // correct guess branch
{
gameOver = true;
System.out.println("Congratulations! Would you like to play again?");
System.out.println("Enter Y for yes or N for no.");
String again = sc.next();
again = again.toUpperCase();
if(again.equals("Y"))
{
GuessingGame3 game;
game = new GuessingGame3();
game.GuessingGame3(); //Start a new game
}
if(again.equals("N"))
{
System.out.println("Goodbye.");
break;
}
}
if(currentGuess > answer) //currentGuess is too high
{
System.out.println("Too high");
}
if(currentGuess <answer) //currentGuess is too low
{
System.out.println("Too low");
}
if(currentGuess > max) //currentGuess is beyond the max
{
System.out.print("Your guess is beyond the max you set.");
continue;
}
int differential = Math.abs(answer - currentGuess);
if (game.differential != 0 && differential < game.differential)
{ // If this is the first guess
System.out.println("Getting Warmer"); // there is differential. So no
} // "warmer" or "colder."
if (game.differential != 0 && differential > game.differential)
{
System.out.println("Getting Colder");
}
game.differential = differential;
}
}
}