【问题标题】:java.lang.ArrayIndexOutOfBoundsException how to remove this error?java.lang.ArrayIndexOutOfBoundsException 如何消除这个错误?
【发布时间】:2016-03-08 00:50:17
【问题描述】:

如何摆脱ArrayIndexOutOfBoundsException

下面是触发异常的代码:

FileReader fr;
try {
 System.out.println(4);
 fr = new FileReader("SOME FILE PATH");
 BufferedReader br = new BufferedReader(fr);

 String in ;
 while (( in = br.readLine()) != null) {
  String[] lines = br.readLine().split("\n");

  String a1 = lines[0];
  String a2 = lines[1];
  System.out.println(a2 + " dsadhello");
  a11 = a1;

  String[] arr = a11.split(" ");

  br.close();

  System.out.println(arr[0]);

  if (arr[0].equals("echo")) {

   String s = a11;

   s = s.substring(s.indexOf("(") + 1);
   s = s.substring(0, s.indexOf(")"));

   System.out.println(s);

   save++;

   System.out.println(save + " save numb");
  }
 }
 System.out.println(3);
} catch (FileNotFoundException ex) {
 System.out.println("ERROR: " + ex);

} catch (IOException ex) {
 Logger.getLogger(game.class.getName()).log(Level.SEVERE, null, ex);
}

这是我从中提取的文件:

echo I like sandwiches (hello thee it work)

apples smell good

I like pie

yes i do

vearry much

【问题讨论】:

  • 一个 ArrayIndexOutOfBoundsException 意味着您正在尝试从一个长度太小而无法找到该值的数组中读取索引。 (例如,看看如果你在一个长度为 5 的数组上调用 array[10] 会发生什么)
  • @XxGoliathusxX 我将您的评论标记为不具建设性。无论如何,这对OP没有帮助。对于初学者来说,任何异常都很难找到/处理,所以你不需要通过说它容易或说他们的代码“可怕”来侮辱他/她。另外,确实,try catch 可以用来处理异常,但是 frenchtoaster 想要的是找到原因并消除它。
  • @ostrichofevil 说了什么。只是想添加(作为一般提示):记住索引在 java 中从 0 开始!仅仅因为你声明了一个数组new int[10],并不意味着它的索引为10。这意味着它有十个元素是0-9。引用array[10] 将抛出ArrayIndexOutOfBoundsException

标签: java arrays bufferedreader


【解决方案1】:

下面这行很可能会产生异常:

String a2 = lines[1];

我们正在使用br.readLine() 从文件中读取。此方法仅读取一行并将其作为String 返回。因为它只有一行,它不会有 '\n',因此,用 '\n' 分割它会导致 array 只有一个元素(即 0)。

为了让它工作,我们需要替换下面的行:

String[] lines = br.readLine().split("\n");

String a1 = lines[0];
String a2 = lines[1];
System.out.println(a2 + " dsadhello");

String a1 = in;

我们在这里不需要a2,我们已经在while 循环中读取该行。不用再读了。

【讨论】:

    【解决方案2】:

    在这部分

    String in;
    while ((in = br.readLine()) != null) {
    
        String[] lines = br.readLine().split("\n");
    
        String a1 = lines[0];
        String a2 = lines[1];
        System.out.println(a2 + " dsadhello");
        a11 = a1;
    

    您阅读了一行并忽略它,然后阅读另一行并尝试将其拆分为"\n"。不幸的是,br.readLine() 返回的内容中不会有\n,因此lines 将只有一个元素,并且访问line[1] 是非法的。

    除此之外,你可以简单地写

    while ((all = br.readLine()) != null) {
    

    【讨论】: