如何修复java编程中的“线程中的异常”main“java.lang.ArrayIndexOutOfBoundsException”
我想查看已添加的数据,但它显示异常。可以参考图片如何修复java编程中的“线程中的异常”main“java.lang.ArrayIndexOutOfBoundsException”,java,arrays,indexoutofboundsexception,Java,Arrays,Indexoutofboundsexception,我想查看已添加的数据,但它显示异常。可以参考图片 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 |"
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();
}
当我已经将文本文件中显示的数据一行一行地添加,而不是一行一行地添加,因为我已经在前面添加了数据为了避免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