0

error image i want to view the data that i already add but it shows exception. can refer to the 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();
}

when i already add the data it shows in the text file in one line not in line by line as i already add the data before

Lara Ng
  • 1
  • 1
  • Your array index (the number between the brackets after tokens) is out of bounds (that is, less than zero or more than the last item in the tokens array). – rghome Apr 30 '19 at 11:58
  • post the file contents in question. Your file have not a valid data according to your logic thats why exception occur. – Khalid Shah Apr 30 '19 at 11:58

1 Answers1

-3

To avoid the ArryIndexOutOfBoundException you have to check the size of the tokens array before you expect it to have 8 elements:

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]);
    }
}
Reporter
  • 3,547
  • 5
  • 28
  • 45
Conffusion
  • 4,092
  • 2
  • 13
  • 19