2015-01-21 72 views
0

這個程序只是一本java書籍的解釋程序。然而,在我編譯並運行該程序後,出現運行時錯誤。我是java編程的新手。 的代碼如下:簡單java編程的運行時錯誤nullpointerexception

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) 
+1

的可能重複[什麼是空指針異常,以及如何解決這個問題?( http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – 2015-01-21 06:30:55

+1

@JANNU你應該學會使用調試器。 – Biffen 2015-01-21 06:33:43

回答

3

前三行的startgame()

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

而應該是

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

否則p2(和更高版本p3)是null當您嘗試並訪問它時。

+0

啊打錯了。但我確實知道爲什麼我得到了NullPointerException,所以這很好。我發現的另一個問題是System.out.println命令打印「?」而不是「我」。 – JANNU 2015-01-21 06:47:29

1

p2 and p3從來沒有初始化。一定是一個愚蠢的錯誤,你已經做出了。

請初始化變量。

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

你做了錯誤,同時啓動對象

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

更正代碼:

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