简体   繁体   中英

NullPointerException runtime error

I'm pretty new to java and working on a program that should simulate the Mastermind game. Here's the description: Write an application in Java that allows a user to play the game Bulls and Cows against a computer. The game works as follows: The computer chooses a 4-digit number in secret. The digits must all be different. The user then guesses the number and the computer provides the number of matching digits. If the matching digit is in the right position it is a "bull", if it is on a different position it is a "cow"

There are two classes that I'm allowed to have: Oracle and Game. Oracle class generates the 4-digit number that computer picks and calculates the number of bulls and cows in the player's guess. Game class gets the number of bulls and cows from Oracle and reports it. I'm getting this error when I run the program:

the error appears to be here: at Game.play(Game.java:34) at BullsAndCows.main(BullsAndCows.java:5)

Can you help me figure out what's wrong? Thanks a lot.

these are the images of Oracle and Game classes as well as the main method

Oracle's member variable computer is not initialized.

That's because on Oracle's constructor, you're not initializing the member variable computer , but another variable with the same name, that's local to the method.

To fix it, on line 21 of Oracle, replace this:

Oracle computer = new Oracle();

by this:

computer = new Oracle();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM