IndexOutOfBoundsException错误
public void thisisnotworking() { Scanner input=new Scanner(System.in); String cardA; String cardB; System.out.print("Enter Card: "); cardA=input.nextLine(); System.out.print("Enter Card "); cardB=input.nextLine(); Card a = game.get(game.indexOf(cardA)); Card b = game.get(game.indexOf(cardB));
这段代码是我编写的方法的一部分。 基本上,用户输入的卡是arrays列表中的一张卡,然后是另一张卡。 目前,当我运行这部分代码时,我收到了IndexOutOfBoundsException错误。
谁能告诉我它有什么问题?
没有看到game
很难说,但似乎cardA
和cardB
不在game
,所以game.indexOf(cardA)
返回-1而game.get(-1)
抛出exception。
另外,查看代码,在game
搜索String
,然后从game
获取一个元素,即String
,并将其分配给Card
对象。 您不能从String转换为除Object
之外的任何其他类,因为String
是最终类。
你把卡片放在哪里进入游戏? 如果没有可能缺少的代码,则需要调用
game.set(cardA); game.set(cardB);
在game.get(...);
之前game.get(...);
尝试这个…
public void thisshouldwork() { Scanner input=new Scanner(System.in); String cardA; String cardB; System.out.print("Enter Card: "); cardA=input.nextLine(); System.out.print("Enter Card "); cardB=input.nextLine(); game.add(cardA); game.add(cardB); Card a = game.get(game.indexOf(cardA)); Card b = game.get(game.indexOf(cardB));
问题是你没有将cardA或cardB添加到游戏中,因此indexOf
返回-1并抛出IndexOutOfBounds Exception
您必须将readLine
方法的返回值readLine
转换为Object
,然后调用toString()
方法:
cardA=((Object)in.readLine()).toString();