【问题标题】:How to fix "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException" in java programming [duplicate]如何在java编程中修复“线程“主”java.lang.ArrayIndexOutOfBoundsException中的异常”[重复]
【发布时间】:2019-04-30 11:54:24
【问题描述】:

error image 我想查看我已经添加但显示异常的数据。可以参考图片

public static void viewRecord()throws IOException{
    File f= new File("file.txt");          // specify the file name and path here
    Scanner sc = new Scanner(f);
    System.out.println("ID  |Species    |Weight |Length |"
                       +"Num of working flippers|Time   |Date   |Location   |");
    while(sc.hasNextLine())
    {
        String currentLine= sc.nextLine();
        String[] tokens = currentLine.split("#");
        System.out.println(tokens[0]+"\t"+tokens[1]+"\t\t"
                           +tokens[2]+"\t"+tokens[3]+"\t"+tokens[4]+"\t\t"+tokens[5]+"\t"
                           +tokens[6]+"\t"+tokens[7]);
    }
    sc.close();
}

当我已经添加了它在文本文件中显示的一行而不是一行一行的数据时,因为我之前已经添加了数据

【问题讨论】:

  • 您的数组索引(tokens 后面括号之间的数字)超出范围(即小于零或大于 tokens 数组中的最后一项)。
  • 发布有问题的文件内容。根据您的逻辑,您的文件没有有效数据,这就是发生异常的原因。

标签: java arrays indexoutofboundsexception


【解决方案1】:

为避免 ArryIndexOutOfBoundException,您必须先检查令牌数组的大小,然后再预计它有 8 个元素:

while(sc.hasNextLine())
{
    String currentLine= sc.nextLine();
    String[] tokens = currentLine.split("#");
    if(tokens.length<8) {
        System.out.println("Invalid format in line:"+currentLine;
    } else {
        System.out.println(tokens[0]+"\t"+tokens[1]+"\t\t"+tokens[2]
          +"\t"+tokens[3]+"\t"+tokens[4]+"\t\t"+tokens[5]+"\t"
          +tokens[6]+"\t"+tokens[7]);
    }
}

【讨论】:

  • 如果您不喜欢这个答案,请告诉我原因,以便我从中学习
  • 我没有投反对票,但是这个问题之前已经被问过很多次,并且已经在重复的问题中得到了回答。在我看来,最好关闭并继续前进。
  • 好的谢谢你的时间@rghome
猜你喜欢
  • 2013-12-18
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 2021-06-13
  • 2011-07-07
相关资源
最近更新 更多