-2

我正在创建一个面向对象的策划游戏。我已经设置了所有的类和方法,并以非面向对象的编程风格尝试了它们,它们都可以工作,但是现在因为我将它们设置为面向对象的风格,所以我得到了空指针错误。它告诉我错误发生在哪里,我试图弄清楚什么是空值或什么是错误的,但我无法弄清楚。我还尝试删除发生 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;
}   
}
4

3 回答 3

6

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

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

}
于 2012-10-18T17:49:55.987 回答
3

在属性声明上使用 final 可以强制实例的生命周期,并且不需要构造函数:

public class MasterMind 
{
   private final Master theMaster = new Master();
   private final Player thePlayer = new Player();
于 2012-10-18T17:53:43.993 回答
0

-首先,您应该有一个constructor带有 的名称Class带有 No 的名称return type

- Amethod可以与 the同名class会有一个 return type.

尝试这样的事情:

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

}
于 2012-10-18T17:53:37.843 回答