java.lang.ArrayIndexOutOfBoundsException:10尽管数组最多可以达到10

时间:2014-12-16 22:08:31

标签: java arrays error-handling file-management

我得到一个" java.lang.ArrayIndexOutOfBoundsException:10"错误在我的"如果"即使从中获取数据的文件的索引也足够为10。

当我在我的代码中的其他地方拨打信息[10]时,它可以正常工作,但我不知道它为什么不在这里工作。

现在学习计算机科学的文件管理单元......

public static void comSci(String onTheMap) throws IOException  
{         
    BufferedReader input = new BufferedReader (new FileReader ("data.txt"));
    if (onTheMap.equals("3")){    
        Scanner scanner = new Scanner("data.txt");
        String line="x";
        System.out.println("--------------------------------------------------------------");
        System.out.println("Create a file of student's who are enrolled in ICS3U0:");
        System.out.println("--------------------------------------------------------------");
        String info[] = new String[20];
        boolean finder = false;      

        while (line!=null) {
            line = input.readLine();
            if (line==null)
                break;        
            info = line.split(",");

            if (info[10].toLowerCase().contains("ICS3U0".toLowerCase())) {  //PROBLEM
                finder = true;
                String programmers = info[0] + "," + info[1];
                System.out.println(programmers);
                try {
                    FileWriter theFile = new FileWriter("ICS3U0.txt",true);
                    PrintWriter names = new PrintWriter(theFile);
                    names.println();
                    names.close();

                }
                catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }  
        } 
        System.out.println("ICS3U0.TXT WAS CREATED");

    }
    input.close();

}

1 个答案:

答案 0 :(得分:2)

Java数组索引从0开始。因此,长度为10的数组具有0-9(包括0-10)的有效索引。这就是for循环通常设置样式的原因,

for (int i = 0; i < arr.length; i++) { // <-- less than (not less than =).
   // ...
}