我有一个ArrayList,里面填充了Result类的对象。每个结果都有一个名为Category的属性。
我正在尝试使用for循环创建方法,该方法使用来自用户的输入类别打印出每个结果。
目前for循环有效,但if-statement分隔是否打印出结果不起作用,这就是我正在搜索的帮助。
自从我尝试了所有其他代码以来,单独使用if语句是我认为目前无效的。
String categoryToPrint;
System.out.println("Which category would you like to print out results for?");
categoryToPrint = scanner.nextLine();
categoryToPrint = normalisera(grenAttVisa); //method making all letters small and first letter capital.
System.out.println("Resultlist for" + categoryToPrint );
for (int i = 0; i < resultlist.size(); i++) {
Athlete matched = null;
Result res = resultlist.get(i);
if (res.categoryName().equals(categoryToPrint)) {
for (int x = 0; x < resultlist.size(); x++) {
Athlete del = athletes.get(x);
if (res.athleteStartNumber() == del.startNumber()) {
matched = del;
break;
}
}
System.out.println(matched.surName() + " " + matched.lastName() + " has the result: " + res.categoryValue());
}
}
答案 0 :(得分:1)
更改
for (int x = 0; x < resultlist.size(); x++)
到
for (int x = 0; x < athletes.size(); x++)
让我们暂时考虑一下这种情况:
resultlist = [result1, result2, result3] // size() == 3
athletes = [athlete1, athlete2] // size() == 2
依靠您的实际代码:
for (int i = 0; i < resultlist.size(); i++) {
for (int x = 0; x < resultlist.size(); x++) {
Athlete del = athletes.get(x);
...
以下是外循环第一次迭代中内循环的方法:
resultlist.size() == 3
i == 0, x == 0 ====> Athlete del = athletes.get(0); // x < 3, good
i == 0, x == 1 ====> Athlete del = athletes.get(1); // x < 3, good
i == 0, x == 2 ====> Athlete del = athletes.get(2); // x < 3, good but the athletes arraylist has only 2 elements, Exception raised