我有一个字符串数组,如:
String [] teams = {"Manchester City", "Chelsea", "Barcelona", "Bayern Munich", "Juventus", "Tottenham", "Liverpool", "Basel", "PSG", "Real Madrid", "Porto" +
"Besiktas", "Sevilla", "Manchester United", "Roma", "Shaktar Donetsk"};
我需要帮助的程序代码:
System.out.print("\nWho do you think will win?: ");
String winner = sc.nextLine();
team: while (teamValid) {
for (int i = 0; i < teams.length ; i++) {
if (!(winner.equalsIgnoreCase(teams[i])))
counter++;
if (counter == 16) {
System.out.print("\nWho do you think will win?: ");
winner = sc.nextLine();
teamValid = false;
break;
}
if ((winner.equalsIgnoreCase(teams[i]))) {
break team;
}
}
}
System.out.println(winner);
我想要做的是提示用户输入此String数组中的一个团队。如果他输入错误的名称(忽略案例),那么我再次要求进入该团队。这就是我所拥有的。我理解我的逻辑错误发生在:
if (counter == 16) {
System.out.print("\nWho do you think will win?: ");
winner = sc.nextLine();
teamValid = false;
break;
}
我怎样才能解决这个问题?
您可以使用do while循环,而使用Java 8可以解决您的问题,如下所示:
String winner; boolean check;
do {
System.out.print("\nWho do you think will win?: ");
winner = sc.nextLine();
//check if there are a team in your array, with (ignoring cases)
check = Arrays.asList(teams).stream().anyMatch(winner::equalsIgnoreCase);
} while (!check);
System.out.println(winner);
你在团队中进行迭代,这没有任何意义。
相反,你应该尝试:
do {
potentialWinner = sc.read()
for (each team){
if (potentialWinner.ignoreCaseEquals(team)
winner = potentialWinner
break
}
} while (winner == null)
考虑这样的事情:
input: while (true) {
String winner = sc.nextLine();
for (String name : teams) {
if (winner.equalsIgnoreCase(name)) {
break input;
}
}
}
这将接受输入并检查它是否存在于Array中。如果没有,它将提示用户输入另一个输入并重复通过数组直到找到有效输入。
假设您正在使用Java 8+,您可以使用Arrays.asList
将String[]
转换为List
,然后在Predicate<String>
循环中使用winner::equalsIgnoreCase
中的do-while
。你可以negate()
Predicate
确定“其他人”。喜欢,
String[] teams = { "Manchester City", "Chelsea", "Barcelona", "Bayern Munich",
"Juventus", "Tottenham", "Liverpool", "Basel", "PSG", "Real Madrid",
"Porto", "Besiktas", "Sevilla", "Manchester United", "Roma", "Shaktar Donetsk" };
List<String> teamList = Arrays.asList(teams);
Scanner sc = new Scanner(System.in);
String winner;
do {
System.out.print("\nWho do you think will win?: ");
winner = sc.nextLine();
} while (!teamList.stream().anyMatch(winner::equalsIgnoreCase));
System.out.printf("You like %s?%n", winner);
Predicate<String> predicate = (Predicate<String>) winner::equalsIgnoreCase;
System.out.printf("I think %s will knock them out this year%n", teamList.stream()
.filter(predicate.negate()).collect(Collectors.joining(" or ")));
示例运行:
Who do you think will win?: basel
You like basel?
I think Manchester City or Chelsea or Barcelona or Bayern Munich or Juventus or Tottenham or Liverpool or PSG or Real Madrid or Porto or Besiktas or Sevilla or Manchester United or Roma or Shaktar Donetsk will knock them out this year