运行 简单 java 程序的时间错误 nullpointerexception

run time error nullpointerexception for simple java prog

这个程序只是 java 书中的解释程序。然而,在我编译 运行 程序后,我得到了 运行 时间错误。我是 java 的编程新手。 代码如下:

class GuessGame{
  Player p1;
  Player p2;
  Player p3;
  public void startgame(){
    p1=new Player();    
    p1=new Player();
    p1=new Player();
    int guessp1=0;
    int guessp2=0;
    int guessp3=0;
    boolean p1isRight=false;
    boolean p2isRight=false;
    boolean p3isRight=false;
    int targetNumber= (int) (Math.random() * 10);
    System.out.println("Ï am thinking of a number between 0 and 9");
    while(true){
    p1.guess();
    p2.guess();
    p3.guess();
    guessp1=p1.number;
    System.out.println("Player 1 guessed " +guessp1);
    guessp2=p2.number;
    System.out.println("Player 2 guessed " +guessp2);
    guessp3=p3.number;
    System.out.println("Player 3 guessed " +guessp3);
    if(guessp1==targetNumber)
      p1isRight=true;
    if(guessp2==targetNumber)
      p2isRight=true;
    if(guessp3==targetNumber)
      p3isRight=true;
    if(p1isRight || p2isRight || p3isRight){
        System.out.println("We have a winner!!");
        System.out.println("Player 1 got it right ?" +p1isRight);
        System.out.println("Player 2 got it right ?" +p2isRight);
        System.out.println("Player 3 got it right ?" +p3isRight);
        System.out.println("Game Over");
        break;
    }
    else{
        System.out.println("Players will have to try again");
    }
    }
  }
}

class Player{
    int number=0;
    public void guess(){
        number= (int) (Math.random() * 10); 
        System.out.println("Ï am guessing " +number);
    }
}

public class GameLauncher{
  public static void main(String [] args){
    GuessGame game=new GuessGame();
    game.startgame();
  }
}

我得到的错误是:

? am thinking of a number between 0 and 9
? am guessing 0
Exception in thread "main" java.lang.NullPointerException
        at GuessGame.startgame(GameLauncher.java:19)
        at GameLauncher.main(GameLauncher.java:59)

startgame()的前三行是

p1=new Player();    
p1=new Player();
p1=new Player();

但应该是

p1=new Player();
p2=new Player();
p3=new Player();

否则 p2(以及后来的 p3)在您尝试访问它时是 null

p2 and p3 永远不会被初始化。一定是你犯了一个愚蠢的错误。

请初始化变量。

p1=new Player();    
p2=new Player();
p3=new Player();

您在启动对象时犯了错误

        p1=new Player();    
        p1=new Player();
        p1=new Player();

更正后的代码是:

        p1=new Player();    
        p2=new Player();
        p3=new Player();