比較兩個字符串我得到這個錯誤信息,我不太清楚什麼是錯:空指針異常在Java中
Exception in thread "main" java.lang.NullPointerException
at Risk.runTeams(Risk.java:384)
at Risk.blobRunner(Risk.java:220)
at Risk.genRunner(Risk.java:207)
at Risk.main(Risk.java:176)
這裏是代碼的相關位(我將在提請注意行號通過代碼中的註釋,以及輸入錯誤消息我投入計劃,而其運行的位置有關)
public class Risk
{
...
public static void main (String[]arg)
{
String CPUcolor = CPUcolor() ;
genRunner (CPUcolor) ; //line 176
...
}
...
public static void genRunner (String CPUcolor) // when this method runs i select 0 and run blob since its my only option. Theres nothing wrong with this method so long as i know, this is only significant because it takes me to blob runner and because another one of our relelvent line numbers apears.
{
String[] strats = new String[1] ;
strats[0] = "0 - Blob" ;
int s = chooseStrat (strats) ;
if (s == 0) blobRunner (CPUcolor) ; // this is line 207
}
...
public static void blobRunner (String CPUcolor)
{
System.out.println ("blob Runner") ; int turn = 0 ; boolean gameOver = false ;
Dice other = new Dice ("other") ;
Dice a1 = new Dice ("a1") ; Dice a2 = new Dice ("a2") ; Dice a3 = new Dice ("a3") ;
Dice d1 = new Dice ("d1") ; Dice d2 = new Dice ("d2") ;
space (5) ;
Territory[] board = makeBoard() ;
IdiceRoll (other) ;
String[] colors = runTeams(CPUcolor) ; //this is line 220
Card[] deck = Card.createDeck() ;
System.out.println (StratUtil.canTurnIn (deck)) ;
while (gameOver == false)
{
idler (deck) ;
board = assignTerri (board, colors) ;
checkBoard (board, colors) ;
}
}
...
public static String[] runTeams (String CPUcolor)
{
boolean z = false ;
String[] a = new String[6] ;
while (z == false)
{
a = assignTeams() ;
printOrder (a) ;
boolean CPU = false ;
for (int i = 0; i<a.length; i++)
{
if (a[i].equals(CPUcolor)) CPU = true ; //this is line 384
}
if (CPU==false)
{
System.out.println ("ERROR YOU NEED TO INCLUDE THE COLOR OF THE CPU IN THE TURN ORDER") ;
runTeams (CPUcolor) ;
}
System.out.println ("is this turn order correct? (Y/N)") ;
String s = getIns() ;
while (!((s.equals ("y")) || (s.equals ("Y")) || (s.equals ("n")) || (s.equals ("N"))))
{
System.out.println ("try again") ;
s = getIns() ;
}
if (s.equals ("y") || s.equals ("Y"))
z = true ;
}
return a ;
}
...
} // This } closes the class
我不認爲我應該得到一個null的原因:pointerException是因爲在這一行:a[i].equals(CPUcolor)
在索引處我有一個字符串,CPUcolor是一個字符串。在這一點上,肯定有一個值既不是空值。任何人都可以告訴我最新錯誤?
你是對的[0]是空的。改變我的陳述,比較兩個字符串,所以我開始爲1修復了問題 – David 2010-04-16 18:20:10
@David - 我很高興你擺脫了這個異常,但是改變for循環的下界會讓程序正常工作嗎?你真的打算只有* 5 *團隊? – JeffH 2010-04-16 18:31:24
assign groups方法返回一個長度爲7的字符串數組。第一個數組被放棄。 – David 2010-04-17 18:24:37