简体   繁体   中英

Array is getting index out of bounds in one specific spot of text file

So I have a text file with very simple text. Each line is simply make,model,vin#. I have about 3 or 4 lines to test. When I print out these lines, only the lines with even indexes get printed. If I don't include the else statement then it gives an out of bounds exception. So for example, with text file input as shown

Hi guys. I have a text file that is only a few lines long. On each line, it is formatted as such: make,model,number . When I run my program, it prints the lines normally until it gets to the third line of the text file(there's only 5 lines). This third line is where I get the index out of bounds exception .

public CarDealershipSystem(File carFile, File associateFile) {

    try (BufferedReader br = new BufferedReader(new FileReader(carFile))) {
        String line;
        for(;;) {
            line = br.readLine();
            String[] lineArray = line.split(",");
            System.out.println(lineArray[0]);
            System.out.println(lineArray[1]);
            System.out.println(lineArray[2]);
        }
    }catch(IOException e) {
        e.getLocalizedMessage();
        e.printStackTrace();
    }
    

You have "line = br.readLine()" in two places in "while" cycle and in "if" block that causes two calls to readLine per cycle. Besides this block is pointless because the "while" condition already handles it.

tldr: remove

if((line = br.readLine()) == null) {
                break;
            }
  1. you need a break when you reach the end of the file.
String line;
while((line = br.readLine()) != null) { //stop loop when line == null
            line = br.readLine();
       }

  1. you need to check your input, before split
String[] lineArray = line.split(",");
if (lineArray != null && lineArray.length == 3) { //will help you avoid the ArrayIndexOutOfBoundsException exception 
            System.out.println(lineArray[0]);
            System.out.println(lineArray[1]);
            System.out.println(lineArray[2]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM