简体   繁体   English

NullPointerException运行时错误

[英]NullPointerException runtime error

I'm pretty new to java and working on a program that should simulate the Mastermind game. 我对java很陌生,正在开发一个可以模拟Mastermind游戏的程序。 Here's the description: Write an application in Java that allows a user to play the game Bulls and Cows against a computer. 描述如下:用Java编写一个应用程序,使用户可以在计算机上玩Bulls and Cows游戏。 The game works as follows: The computer chooses a 4-digit number in secret. 游戏的工作原理如下:计算机秘密选择一个4位数字。 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和Game。 Oracle class generates the 4-digit number that computer picks and calculates the number of bulls and cows in the player's guess. Oracle类生成4位数字供计算机选择,并计算玩家猜测中的多头和多头牛。 Game class gets the number of bulls and cows from Oracle and reports it. 游戏类从Oracle获取公牛和母牛的数量并进行报告。 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) 错误似乎在这里:在BullsAndCows.main(BullsAndCows.java:5)的Game.play(Game.java:34)

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和Game类的图像以及主要方法

Oracle's member variable computer is not initialized. Oracle的成员变量computer未初始化。

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. 这是因为在Oracle的构造函数中,您不是在初始化成员变量computer ,而是初始化方法本地的另一个具有相同名称的变量。

To fix it, on line 21 of Oracle, replace this: 要修复此问题,请在Oracle的第21行上替换为:

Oracle computer = new Oracle();

by this: 这样:

computer = new Oracle();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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