对于简单的java prog,运行时错误nullpointerexception

时间:2015-01-21 06:29:28

标签: java nullpointerexception runtime-error

这个程序只是一本来自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)

3 个答案:

答案 0 :(得分:3)

startgame()的前三行是

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

但应该是

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

当您尝试访问时,p2(以及后来的p3)为null

答案 1 :(得分:1)

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

请初始化变量。

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

答案 2 :(得分:1)

启动对象时你确实错了

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

更正后的代码是:

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