我在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);
}
答案 0 :(得分:0)
您正在阅读一行。因此,您可以输入&#34;等级强度&#34;。
同样通过在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);
}
答案 1 :(得分: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);
}
尝试一下,让我们知道结果是什么。
答案 2 :(得分:0)
摆脱对readLine()
的第二次调用。它不是一个功能,它是一个错误。您已经拥有了下一行,并且您已经将其检查为null。没有必要将它扔掉并获得另一个未经检查的。