将字符串存储到数组中会导致ArrayIndexOutOfBoundsException错误

时间:2013-07-31 15:16:39

标签: java

int x = 0;
String[] QEquivalent = {};

String s = sc.nextLine();
String[] question2 = s.split(" ");

for (int i = 0; i < question2.length; i++) {
    System.out.println(question2[i]);
    x++;
}                                                                   //debug
System.out.println(x);

String s2 = sc2.nextLine();
String[] Answer = s2.split(" ");

for (int c = 0; c < Answer.length; c++) {
    System.out.println(Answer[c]);
}                                                                   //debug
int y;

String u = sn.nextLine();
String[] t = u.split(" ");
for (y = 0; y < question2.length; y++) {
    for (int w = 0; w < t.length; w++) {
        if (t[w].equals(question2[y])) {
            QEquivalent[y] = "ADJ";
            System.out.println(QEquivalent[y]);
            break;
        }
    }
}

这是我现在拥有的代码行。当在String [] t中找到question2中的字符串时,它应该将字符串“ADJ”存储在String [] QEquivalent中。我似乎无法修复错误。有人可以帮帮我吗?

7 个答案:

答案 0 :(得分:3)

你在这里创建一个空数组:

String[] QEquivalent = {};

因此,您尝试访问的任何索引都将超出范围。您应该使用固定大小创建一个数组。

或者,您可以更好地使用ArrayList,它可以动态增长:

List<String> qEquivalent = new ArrayList<String>();

然后使用:

添加元素
qEquivalent.add("ADJ");

请遵循Java命名约定。变量名称应以小写字母开头。

答案 1 :(得分:1)

您的数组QEquivalent是一个空数组。它的长度为0,因此即使QEquivalent[0]也会抛出ArrayIndexOutOfBoundsException

我能看到的一个解决方法是为它分配一个长度:

String[] question2 = s.split(" ");
// Just assign the dimension till which you will iterate finally
// from your code `y < question2.length` it seems it should be question2.length
// Note you are always indexing the array using the outer loop counter  y 
// So even if there are n number of nested loops , assigning the question2.length
// as dimension will work fine , unless there is something subtle you missed 
// in your code
String[] QEquivalent = new String[question2.length];

更好地使用List的任何实现,例如ArrayList

List<String> qEquivalent = new ArrayList<String>();
......
if (t[w].equals(question2[y])) {
       qEquivalent.add("ADJ");
       System.out.println(qEquivalent.get(y));
       break;
}

答案 2 :(得分:1)

您创建一个空数组:

String[] QEquivalent = {};

然后在索引y > 0处设置一些元素:

QEquivalent[y] = "ADJ";

你可以:

  • 计算数组的最终维度,并确保实例化它:String[] QEquivalent = new String[SIZE];
  • 使用像ArrayList
  • 这样的动态结构

例如:

ArrayList<String> QEquivalent = new ArrayList<QEquivalent>(); 
QEquivalent.add("ADJ");

答案 3 :(得分:0)

为数组String[] QEquivalent = new String[100];

指定一些大小

你声明String[] QEquivalent = {};创建一个零大小的数组。

答案 4 :(得分:0)

您宣布QEquivalent array为空String array

当您访问索引QEquivalent[y]时,该索引不存在,因此ArrayIndexOutOfBoundsException

我强烈建议您改用List<String>

如:

List<String> qEquivalent = new ArrayList<String>(); // replaces the array declaration and uses Java conventional naming

...

qEquivalent.add("ADJ"); // replaces the indexing of the array and adds the item

答案 5 :(得分:0)

可能QEquivalent变量产生错误。因为当你声明那个变量时,它的长度是0.所以用new和一个大小来声明变量。

答案 6 :(得分:0)

或者在将字符串拆分为question2并使用:

后移动它
String[] QEquivalent = new String[question2.length];