我正在创建一个面向对象的策划游戏。我已经设置了所有的类和方法,并以非面向对象的编程风格尝试了它们,它们都可以工作,但是现在因为我将它们设置为面向对象的风格,所以我得到了空指针错误。它告诉我错误发生在哪里,我试图弄清楚什么是空值或什么是错误的,但我无法弄清楚。我还尝试删除发生 null 的点,以便在类似的类型表达式中获得另一个 null 异常。所以我相信我调用方法等的语法错误,但不知道如何修复它,或者它是否是真正错误的原因。
如果您想直接跳转到第二个代码块,则会出现错误。
我知道我在这里发布了很多东西,所以如果您需要任何澄清,我很乐意提供帮助。主要焦点只是空错误,因此如果您看到其他一些错误,请忽略它,除非它妨碍解决空错误。
为了便于阅读,我将每个班级分开。
public class GameTester {
public static void main(String[] args) {
MasterMind m = new MasterMind();
m.playGame();
}
}
public class MasterMind
{
private Master theMaster;
private Player thePlayer;
public void mastermind() {
theMaster = new Master();
thePlayer = new Player();
}
public void playGame() {
System.out.println("WELCOME TO CODEBREAKER... Let's Play!\n");
System.out.println("Guess a 4-letter code with letters A, B, C, and D\n");
theMaster.createCode(); //heres where the null exception is said to occur
while(true) {
thePlayer.makeGuess(); //if i remove the call above this becomes null error
int x = theMaster.totalCorrect(thePlayer.getGuess());
if( x == 4) {
System.out.println("\nGOT IT!!!\n");
}
else {
System.out.printf("MISSED! %d out of 4. TRY AGAIN... \n", x);
}
}
}
import java.util.Random;
public class Master
{
private char[] Code = new char[4];
public Master()
{
}
public void createCode()
{
Random R = new Random();
char[] setting ={'A', 'B', 'C', 'D'};
int rx;
for(int i=0; i<=3; i++)
{
rx = R.nextInt(4);
Code[i] = setting[rx];
}
}
public int totalCorrect(char[] theGuess)
{
int x =0;
if(Code[0] == theGuess[0]) {
x++;
}
if(Code[1] == theGuess[1]) {
x++;
}
if(Code[2] == theGuess[2]) {
x++;
}
if(Code[3] == theGuess[3]) {
x++;
}
return x;
}
}
import java.util.Scanner;
public class Player {
private char[] Guess = new char[4];
public Player() {
}
public void makeGuess() {
System.out.println("YOUR GUESS => ");
Scanner input =new Scanner(System.in);
String guess = input.next();
char[] D = guess.toCharArray();
for(int i=0; i<4; i++) {
Guess[i] = D[i];
}
}
public char[] getGuess() {
return Guess;
}
}