【问题标题】:Array Index Out of Bound using BufferedReader使用 BufferedReader 的数组索引越界
【发布时间】:2015-02-17 03:40:11
【问题描述】:

我在java中遇到ArrayList的问题,所以我尝试使用BufferedReader逐行读取输入,并且输入停止,直到用户发送一个空行。一切正常,直到我尝试逐行阅读。 我想我已经在那个 while() 条件下处理了它,但它返回 ArrayIndexOutofBoundsException

输入示例:

200 200

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Villain> Villains = new ArrayList<Villain>();

String data;
while((data = reader.readLine()) != null)  
{
    data = reader.readLine();
    String[] Split = data.split(" ");
    int level = Integer.parseInt(Split[0]);
    int strength = Integer.parseInt(Split[1]);
    Villain vill = new Villain(level, strength);
    Villains.add(vill);
}   

【问题讨论】:

  • 您检查过String[] Split = data.split(" "); 的长度吗?您确定正在发生这种拆分,因为您正在尝试访问下一行中的元素?
  • 可以查看Split数组的长度,看用户是否输入了空行,例如:if(Split.length &lt; 2){break;}
  • 是否有机会避免使用break; ?
  • 由于您从控制台读取data 变量永远不会是null,这就是为什么您需要从循环中break
  • 是的,我发现了问题,是拆分器试图拆分空行,因为它没有行所以它返回 ArrayIndexoutofBound

标签: java arrays bufferedreader


【解决方案1】:

您正在阅读一行。因此,您将输入“级​​别强度”。

另外,通过将 data = reader.readLine() 放入 while 循环中,之后的行就不需要了。

这是我使用您的代码创建的:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Villain> Villains = new ArrayList<Villain>();

String data;
while((data = reader.readLine()) != null)  
{
    String[] Split = data.split(" ");
    int level = Integer.parseInt(Split[0]);
    int strength = Integer.parseInt(Split[1]);
    System.out.println("Adding data.. level: " + level + ", strength: " + strength);
    Villain vill = new Villain(level, strength);
    Villains.add(vill);
} 

【讨论】:

    【解决方案2】:

    我认为问题在于您正在阅读用户的输入两次。 无论多长,用户一次只能输入一行文本。 这里:

    String data;
    // You read the user's input here and also check if it is not null
    // Remember, it is not only checking if it's null but also reading input
    while((data = reader.readLine()) != null)  
    {
        // Then here again, you try reading the input again
        // Try commenting this line and see if it works.
        data = reader.readLine();
        String[] Split = data.split(" ");
        int level = Integer.parseInt(Split[0]);
        int strength = Integer.parseInt(Split[1]);
        Villain vill = new Villain(level, strength);
        Villains.add(vill);
    }  
    

    试试看,结果如何。

    【讨论】:

      【解决方案3】:

      摆脱对readLine() 的第二次调用。这不是一个功能,这是一个错误。您已经有了下一行,并且已经检查了它是否为空。把它扔掉然后再买一个没有意义的。

      【讨论】:

        猜你喜欢
        • 2013-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多