gpt4 book ai didi

java - java中比较两个字符串的空指针异常

转载 作者:行者123 更新时间:2023-12-01 17:39:40 25 4
gpt4 key购买 nike

我收到此错误消息,但不太确定出了什么问题:

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) a 在索引 i 处持有一个字符串,而 CPUcolor 是一个字符串。此时两者都肯定有一个值,都不为空。谁能告诉我出了什么问题吗?

最佳答案

您应该查看一下 assignTeams() 方法。对于 i 的某些值,a[i] 必须为 null。 CPUcolor 是否为 null 并不重要,equals 方法会处理该问题。

关于java - java中比较两个字符串的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2655216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com