为什么用户在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语句。

chianday 回答:为什么用户在Java中总是得到true的返回值?

这是固定代码。您的代码中存在逻辑缺陷,无论如何都始终返回true。

您还在检查while循环中的条件,如果用户第一次输入ab,则该条件永远不会运行。

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;
 }
本文链接:https://www.f2er.com/1258404.html

大家都在问