无法解决null异常错误

cha*_*hri -2 java null exception object

我正在创建一个面向对象的策划游戏.我已经设置了所有的类和方法,并且以非面向对象的编程风格尝试了它们并且它们都可以工作但是现在因为我以面向对象的方式使用它们我得到空指针错误.它告诉我错误发生在哪里,我试图找出什么是空值或什么是错误但我无法弄明白.我还试图找出null发生的点,只是为了在类似的类型表达式中获得另一个null异常.因此,我认为我在调用方法等方面有错误的语法,但不知道如何修复它或者它是否是真正错误的原因.

如果要直接跳转到第二个代码块,则会发生错误.

我知道我在这里贴了很多东西所以如果你需要任何澄清,我很乐意帮忙.主要焦点是空错误,所以如果你看到其他错误,只要忽略它,除非它阻止解决空错误.

我将每节课分开以便于阅读.


public class GameTester {

public static void main(String[] args) {

    MasterMind m = new MasterMind();
    m.playGame();
    }
}
Run Code Online (Sandbox Code Playgroud)
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);
        }       
    }
 }
Run Code Online (Sandbox Code Playgroud)
  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;
}
}
Run Code Online (Sandbox Code Playgroud)
 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;
}   
}
Run Code Online (Sandbox Code Playgroud)

kos*_*osa 6

你的构造函数应该是完全相同的类,没有返回类型.否则它将被视为方法,并且不会在对象实例化上执行,这会使theMaster引用指向null.

 MasterMind () 
{
    theMaster = new Master();
    thePlayer = new Player();

}
Run Code Online (Sandbox Code Playgroud)