gpt4 book ai didi

java - 如何更改 Java 中创建的对象

转载 作者:行者123 更新时间:2023-12-01 10:54:55 27 4
gpt4 key购买 nike

以下代码一直有效,直到用户输入团队的分数 int homeScore = input.nextInt() ,此时编译器返回以下错误代码:

Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:854)
at assignment.PremierLeagueManager.main(PremierLeagueManager.java:121)
Java Result: 1

有什么办法可以解决这个问题吗?

boolean validHome = false;
boolean validAway = false;
System.out.println("Enter name of Home team: ");
String homeName = input.next();

Iterator<FootballClub> it = premierLeague.iterator();
while (it.hasNext()) {
if (it.next().getClubName().equals(homeName)) {
validHome = true;
}
}

System.out.println("Enter name of Away team: ");
String awayName = input.next();
Iterator<FootballClub> it2 = premierLeague.iterator();

while (it2.hasNext()) {
if (it2.next().getClubName().equals(awayName)) {
validAway = true;
}
}

if (validHome == true && validAway == true) {
System.out.println("Enter number of goals scored by " + homeName + ":");
int homeScore = input.nextInt();
int x = premierLeague.indexOf(it.next());
premierLeague.get(x).setGoalsScored(homeScore);

System.out.println("Enter number of goals scored by " + awayName + ":");
int awayScore = input.nextInt();
int y = premierLeague.indexOf(it2.next());
premierLeague.get(y).setGoalsScored(awayScore);
} else {
System.out.println("One of the teams are invalid. Please try again");
}

最佳答案

在执行“while (it.hasNext())”的顶部,该循环会一直循环,直到迭代器不再有任何项目,因此当您到达“int x = primeLeague.indexOf(it.next());”时",迭代器没有下一个项目,因此您没有得到这样的元素。如果你想重新开始,你需要创建一个新的迭代器。

关于java - 如何更改 Java 中创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com