Java BufferedReader while loop out of bounds exception

吃可爱长大的小学妹 提交于 2019-12-11 10:48:38

问题


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) {

       }    

     }

  }

回答1:


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);

 }



回答2:


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


来源:https://stackoverflow.com/questions/25191648/java-bufferedreader-while-loop-out-of-bounds-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!