【问题标题】:ArrayIndexOutOfBounds Exception, but not out of bounds?ArrayIndexOutOfBounds 异常,但没有越界?
【发布时间】:2018-05-11 17:22:54
【问题描述】:

我正在编写一种编辑 CSV 文件中记录的方法,该方法应打印除正在编辑的行之外的所有内容,然后将编辑后的版本打印到新文件中。

while((line = br.readLine()) != null) {
            if(line.contains("PATRON")) {
                pw.println(line);
            }
            if(!line.contains("PATRON")) {
                String[] str = line.split(",", 7);

                if(str[1].equals(ID)) {
                    pw.println(str[0] + "," + ID + "," + str[2] + "," + "false" + "," + "0" + "," + str[5] + "," + "0");
                }else {
                    pw.println(line);
                }
            }
        }

当我尝试运行它并输入一个有效的 ID 时,它给了我这个异常

java.lang.ArrayIndexOutOfBoundsException: 1
at myproject.Materials.returnmat(Materials.java:296)
at myproject.Library.mmenu(Library.java:121)
at myproject.Library.mainmenu(Library.java:143)
at myproject.Library.main(Library.java:11)

但是在运行了一些测试之后,

for(int x=0;x<str.length;x++) {
                    System.out.println(x+ ": " +str[x]);
                }

它输出的正是 id 所期望的,1:101、1:102 等。 所以这表明我的 ID 肯定在 str[1] 索引处。

为什么会抛出异常?

编辑:如果它相关,这就是我如何称呼它。

    case "7": 
            System.out.println("Enter material ID: ");
            String matsid = scan.nextLine();
            mats.returnmat(matsid);
            scan.nextLine();
            break;

【问题讨论】:

  • 为什么要添加循环来调试?只需在触发错误的行之前添加一个打印语句。我会添加一个计数变量来查看触发错误的(文件的)行号,然后我会打印出 line 和 str 以查看错误发生的原因。

标签: java arrays indexoutofboundsexception


【解决方案1】:

在执行 if(str[1].equals(ID)) {

之前检查您的字符串长度

类似:

if(str.length<1) { 
    System.out.println("line no good="+line); 
} else ...

您可能在 CSV 中有一行错误,或者这是最后一个空白行。

【讨论】:

  • 我添加了这个和其他一些调试行,最后它的打印字符串不好,所以它看起来像它的最后一个空行,为什么阅读器没有停止,因为它是一个空行?
  • 因为 Java 会解释 readline 函数中的最后一个 /r/n 或“换行符”。
【解决方案2】:

这里

        String[] str = line.split(",", 7);
        if(str[1].equals(ID)) {

分割线必须返回长度为 1 的数组,因此最大索引为 0 - 但您使用 str[1] 超过了它;

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 2018-07-12
    • 1970-01-01
    • 2018-06-07
    • 2013-11-28
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多