简体   繁体   English

Java BufferedReader while循环超出范围异常

[英]Java BufferedReader while loop out of bounds exception

I am using BufferedReader to read data from a text file. 我正在使用BufferedReader从文本文件读取数据。 The variable "reg" is the fourth entry in the string of data that I am trying to access. 变量“ reg”是我要访问的数据字符串中的第四个条目。

I am getting the exception: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3" 我收到异常:“线程“主”中的异常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. 错误是储液池(有时)的长度小于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: 异常是ArrayIndexOutOfBoundsException.Oracle文档说:

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. 错误-> java.lang.ArrayIndexOutOfBoundsException:3表示您正在尝试访问索引3。

The line which is accessing index 3 is 正在访问索引3的行是

   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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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