Java ArrayIndexOutofBoundsArrayList的异常数组
我创建了一个ArrayList数组,其大小为45。出于某种原因,我收到了一份BoundException的安排 这里是我得到错误的地方:Java ArrayIndexOutofBoundsArrayList的异常数组,java,arrays,arraylist,indexoutofboundsexception,Java,Arrays,Arraylist,Indexoutofboundsexception,我创建了一个ArrayList数组,其大小为45。出于某种原因,我收到了一份BoundException的安排 这里是我得到错误的地方: String temp; Scanner sc = new Scanner(str1); while(sc.hasNext()) { temp = sc.next(); int len = temp.length(); if(len > 0) word
String temp;
Scanner sc = new Scanner(str1);
while(sc.hasNext())
{
temp = sc.next();
int len = temp.length();
if(len > 0)
wordsByLen[len - 1].add(temp); //throwing the error here with exception of 59
}
提前感谢您的帮助 您是否已正确初始化数组
wordsByLen
?我想不是
我认为您需要做的是使用正确的长度初始化数组,然后使用每个可能单词长度的集合。e、 g.(伪代码)
for(int i=0;i
我可能会使用
地图
。您必须以类似的方式初始化它,但这将是一种更可靠的机制。您不会对可以记录单词的最大字符数有任意限制。单词定义在哪里?什么可以确保temp.length()
永远不会超过45?您正在读取我在类的构造函数中定义的wordsByLen的字符串。我可以看到您假设temp.length()将返回0到44之间的值。这是真的吗?这可能是问题的原因。请尝试在出现if
条件之前打印len
的值,并查看您得到的值是什么。我是在构造器里做的。在我这么做之前,我在同一行得到了一个NullPointerException。我只是没有包含代码,因为我认为没有必要。当你只能存储最多45个字符的单词的信息时,你会发现一个59个字符的单词。上面的解决方案(使用地图)将绕过这个问题。我的任务是限制为45。谢谢你的建议,但那对我不起作用。
for (int i = 0; i < MAXWORDLENGTH; i++) {
wordsByLen[i] = new ArrayList<String>();
}