问题描述
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));
此代码是我编写的方法的一部分。基本上,用户输入的卡是阵列列表中的一张卡,然后是另一张卡。目前,当我运行这部分代码时,我收到了IndexOutOfBoundsException错误。
This code is part of a method i've written. Basically the user inputs the card that is one of the cards in an array list and then another card. Currently I'm getting an IndexOutOfBoundsException error when I'm running this part of the code.
任何人都可以告诉我它有什么问题吗?
Can anyone tell me what is wrong with it?
推荐答案
很难说没有看到游戏
,但似乎 cardA
和 cardB
不在游戏
中,所以 game.indexOf (cardA)
返回 -1 和 game.get(-1)
抛出异常。
It's hard to say without seeing game
, but seems like cardA
and cardB
are not in game
, so game.indexOf(cardA)
returns -1 and game.get(-1)
throws the exception.
另外,查看代码,在游戏
中搜索 String
,然后从游戏
获取一个元素,这是 String
并将其分配给卡
对象。你不能从String转换到 Object
之外的任何其他类,因为 String
是类。
Also, looking at your code, you search for String
in game
, and then takes an element from game
, which is a String
and assigns it to a Card
object. You cannot cast from String to any other class than Object
, since String
is a final class.
这篇关于IndexOutOfBoundsException错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!