如何解决为什么用户在Java中总是得到true的返回值?
public boolean askQuestion(ArrayList < Application.Country > countries) {
int randomNumber = this.getRandomPositionList(countries.size());
Application.Country country1 = countries.get(randomNumber);
int randomNumber1 = this.getRandomPositionList(countries.size());
Application.Country country2 = countries.get(randomNumber1);
System.out.println("Which country has a larger population? ");
System.out.println("a) " + country1.name);
System.out.println("b) " + country2.name);
String userInput = scanner.nextLine();
while (!userInput.matches("[a-b]")) {
System.out.println("Please enter an a or b");
userInput = scanner.nextLine();
if (userInput.matches("a")) {
boolean a = country1.population > country2.population;
} else {
return false;
}
if (userInput.matches("b")) {
boolean b = country1.population > country2.population;
} else {
return false;
}
}
return true;
}
我想向用户询问测验中两个随机国家的人口更多。每次用户使用a或b填写答案时,它都会返回true。我不知道该如何解决。我还在if和else中使用了return语句。
解决方法
这是固定代码。您的代码中存在逻辑缺陷,无论如何都始终返回true。
您还在检查while循环中的条件,如果用户第一次输入a
或b
,则该条件永远不会运行。
public boolean askQuestion(ArrayList < Application.Country > countries) {
int randomNumber = this.getRandomPositionList(countries.size());
Application.Country country1 = countries.get(randomNumber);
int randomNumber1 = this.getRandomPositionList(countries.size());
Application.Country country2 = countries.get(randomNumber1);
System.out.println("Which country has a larger population? ");
System.out.println("a) " + country1.name);
System.out.println("b) " + country2.name);
String userInput = scanner.nextLine();
while (!userInput.matches("[a-b]")) {
System.out.println("Please enter an a or b");
userInput = scanner.nextLine();
}
String answer = (country1.population > country2.population) ? "a" : "b";
if (userInput.matches(answer)) {
return true;
}
return false;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。