2014-10-28 40 views
0

我正在爲遊戲公牛和牛製作代碼(http://en.wikipedia.org/wiki/Bulls_and_cows) 我的代碼編譯了,但是當我嘗試在終端中運行它時,我得到了一個空指針異常錯誤,用於howManyBylls, playOneTurn和playGame。我找不到這個錯誤來自哪裏。此外,該版本的遊戲與其他公牛和牛的遊戲不同,用戶可以輸入四位數的重複數字。我認爲在大多數其他代碼中,他們應該輸入具有唯一數字的四位數字。公牛和牛遊戲程序Java。運行程序時空指針異常錯誤

public int howManyBulls(String guess) 
    { 
    input = guess; 
    bulls = 0; 
    for (int i = 0; i<4; i++) 
    { 
     int k = Integer.parseInt(pattern.substring(i, i+1)); 
     int l = Integer.parseInt(input.substring(i, i+1)); 
     if (k == l) // checking for same value at same location 
     { 


      bulls++; // add one to bull if there is a match 
     } 
    } 
    return bulls; 
    } 


public class Game{ 
    private int turns; 
    private Oracle computer; 
    private Scanner input; 
    public String userInput; 
    public int bulls; 
    public int cows; 

    public Game(){ 
    // creates new data type Oracle 
    computer = new Oracle(); 
    turns = 0; 
    input = new Scanner(System.in); 
    } 

    public void playGame(){ 
    // your code for the Game playGame method goes here 
    System.out.print("Please enter a 4 digit number: "); 
    userInput=input.next(); 
    playOneTurn(); 
    } 

    // plays a turn 
    public void playOneTurn(){ 
    turns++; 

    // passes userInput into methods of howManyBulls() and howManyCows() 
    bulls = computer.howManyBulls(userInput); 
    cows = computer.howManyCows(userInput); 

    System.out.println(bulls+ " bulls"); 
    System.out.println(cows+ " cows"); 

    // checks if game is over 
    if (bulls < 4) // if bulls less than four then continue playing game 
     // if bulls = 4 then the number is correct 
    { 
     playGame(); 
    } else { // done with game and print out number of turns 
     System.out.print("It took" + turns + " turns to guess " 
       + "the correct number"); 
    } 
    } 


    public void setPattern(String solution){ 
     computer.setPattern(solution); 
    } 

    public String getPattern(){ 
     return computer.getPattern(); 
    } 
} 
+1

請包括您在運行程序時獲得的完整堆棧跟蹤。 – Martin 2014-10-28 16:39:49

+2

可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-FIX-IT) – 2014-10-28 16:40:15

+0

請輸入4位數字:1223 異常線程 「main」 顯示java.lang.NullPointerException \t在Oracle.howManyBulls(Oracle.java:68) \t在Game.playOneTurn(遊戲。 java:38) \t at Game.playGame(Game.java:30) \t at BullsAndCows.main(BullsAndCows.java:11)​​ – wics13 2014-10-28 16:43:35

回答

0

它出現在howManyBulls()尚未初始化或已被設置爲null的變量「pattern」中。它沒有在您發佈的代碼中定義,並且是唯一尚未初始化的變量。空指針異常通常是通過調用空對象上的方法引起的,如果變量尚未初始化,則可能發生這種情況。

+0

我創建了一個單獨的方法,將字符串模式定義爲將四個隨機生成的數字連接成一個字符串。 – wics13 2014-10-28 16:57:19

+0

@ wics13你在調用這個方法嗎?換句話說,在調用這個方法之前,'pattern'變量是否被設置? (同時提示,在'howManyBulls'方法中設置一個斷點,並查看哪個變量具體爲null,然後從那裏追蹤它。) – 2014-10-28 17:07:41