我正在爲遊戲公牛和牛製作代碼(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();
}
}
請包括您在運行程序時獲得的完整堆棧跟蹤。 – Martin 2014-10-28 16:39:49
可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-FIX-IT) – 2014-10-28 16:40:15
請輸入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