java.lang.ArrayIndexOutOfBoundsException如何删除此错误?

java.lang.ArrayIndexOutOfBoundsException如何删除此错误?,java,arrays,bufferedreader,Java,Arrays,Bufferedreader,如何消除阵列索引OutofBoundsException 以下是触发异常的代码: 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.re

如何消除
阵列索引OutofBoundsException

以下是触发异常的代码:

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

可能会从以下行生成异常:

字符串a2=行[1]

我们正在使用
br.readLine()
读取文件。此方法只读取一行,并将其作为
字符串返回。因为它只有一行,所以它没有'\n',因此,用'\n'拆分它将导致一个只包含一个元素(即0)的
数组

要使其正常工作,我们需要替换以下行:

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

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

字符串a1=in

我们不需要这里的
a2
,我们已经在
中读取了
循环中的行。无需再次阅读。

在本部分中

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
,因此
将只有一个元素,并且访问
行[1]
将变为非法

尽管如此,你可以简单地写

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

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