数组索引使用BufferedReader进行绑定

问题描述 投票:0回答:3

我在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);
}   
java arrays bufferedreader
3个回答
0
投票

你正在读一行。所以你会使输入“水平强度”。

另外,通过在while循环中放入data = reader.readLine(),它就不需要了。

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

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

0
投票

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

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

试试吧,让我们知道结果是什么。


0
投票

摆脱对readLine()的第二次调用。它不是一个功能,它是一个bug。您已经拥有了下一行,并且您已经将其检查为null。没有必要将它扔掉并获得另一个未经检查的。

© www.soinside.com 2019 - 2024. All rights reserved.