FileReader,ArrayIndexOutOfBounds的奇怪数组情况

时间:2013-05-31 16:02:30

标签: java arrays

我想放弃,但我必须这样做,所以你是我最后的希望。我想这是一个简单的问题,但我看不出有什么问题。这是代码:

    int i = -1;
    String[][] dan = new String[20][13];
    try {
     FileReader odczytanie = new FileReader("Kontrahenci.txt");
     BufferedReader bufor = new BufferedReader(odczytanie);
     String str;
     str = bufor.readLine();
     System.out.println(str);
     while ((str = bufor.readLine()) != null) {
        i = i + 1;
        String[] ar = {null, null, null, null, null, null, null, null, null, null, null, null, null};
        ar=str.split("; ");
        for(int j = 0; j < 13; j++)
            dan[i][j] = ar[j];
        for(int j = 0; j < 13; j++)
            System.out.println(dan[i][j]);  
     }
     bufor.close();
    } catch (IOException e) {
           System.out.println("File Read Error");
        }

因此,当我尝试运行它时,我收到此错误:

"Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1"

这一行:

for(int j = 0; j < 13; j++)
    System.out.println(ar[j]);

在一个文件中,我有三行,用分号分隔单词。代码适用于第一行,但在收到错误后。不知道出了什么问题。

3 个答案:

答案 0 :(得分:0)

硬编码13似乎有点可疑。您为ar设置的值将被拆分分配覆盖。 ar不一定有13个字段。

怎么样?
for (int j = 0; j < ar.length ; j++)

甚至更好

for (String s: ar) 

这些数据必须以某种方式形成错误或不符合您的期望。尝试断言正确的尺寸或打印它。

同样正如Jerry所说,固定大小的阵列是不好的做法。你可以使用一些更高级别的集合,比如一个HashMaps列表或其他自动增长的集合。

一个止损是在用i索引之前检查i < 20然后抛出异常或断言。这将指向正确的方向。您也可以将它添加到while循环中,但这可能会使数据未读。

答案 1 :(得分:0)

String[] ar = {null, null, null, null, null, null, null, null, null, null, null, null, null};
ar=str.split("; ");

这个带有13个空值的ar声明将立即被str.split("; ");覆盖,因此您不能假设数组的大小始终为13.而不是使用13作为上层你的for循环的界限我建议使用ar.len或尝试每个循环。

我怀疑您的IndexOutOfBoundsError数组也会有相同的dan

你应该避免使用幻数。

答案 2 :(得分:0)

您应该在创建阵列之前弄清楚文件中有多少行,或者切换到允许更改大小的内容:

ArrayList<String[]> dan = new  ArrayList<String[]>();
try
{
    BufferedReader bufor = new BufferedReader(new FileReader("Kontrahenci.txt"));
    while (bufor.ready())
    {
        dan.add(bufor.readLine().split("; "));
    }
    bufor.close();
}
catch (IOException e)
{
    System.out.println("File Read Error");
}

for(String[] ar : dan)
{
    for(String s : ar)
    {
        System.out.println(s);
    }
}

我没有更改您的错误处理,但请注意,如果有异常,您将不会致电close

相关问题