简体   繁体   中英

Java BufferedReader while loop out of bounds exception

I am using BufferedReader to read data from a text file. The variable "reg" is the fourth entry in the string of data that I am trying to access.

I am getting the exception: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3"

Here is my code:

package calctest;

import static calctest.CalcTest.reg;
import java.io.*;

public class CalcTest {

    static Integer reg, prov;

public static void main(String[] args) throws Exception{

String readFile = "M:\\MandNDrives\\mwallace\\JAVA for NEMS\\EORModule\\NEMSEORDB.txt";
    BufferedReader br = null;
    String line = "";
    String delim = "[ ]+";

    try {        
        br = new BufferedReader(new FileReader(readFile));
        br.readLine();
        while ((line = br.readLine()) != null) {

            String [] reservoir = line.split(delim);

            reg = Integer.parseInt(reservoir[3]);

            System.out.println(reg);

         }
         }catch (FileNotFoundException e) {
         }catch (IOException e) {

       }    

     }

  }

Your error has nothing to do with the reading. The error is that reservoir (sometimes) has a length less than 4.

 while ((line = br.readLine()) != null) {
        String [] reservoir = line.split(delim);

        for(String s : reservoir)
            System.out.println(s);  //Post what this outputs for debugging purposes

        if (resivoir.length > 3)
            reg = Integer.parseInt(reservoir[3]);
        else
            reg = ... //do something else...

        System.out.println(reg);

 }

The exception is ArrayIndexOutOfBoundsException.Oracle docs says:

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

The error->java.lang.ArrayIndexOutOfBoundsException: 3 means you are trying to access index 3.

The line which is accessing index 3 is

   reg = Integer.parseInt(reservoir[3]);

please put a check like following

 if (resivoir.length > 3)
            reg = Integer.parseInt(reservoir[3]);
        else
            //there must be some error or do something else

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