我用scanner写的一个方法class好像没有结束

A method that I wrote with a scanner class doesn't seem to end

我写了一个方法来让用户选择网格的大小。但是,我的代码在执行该方法后似乎不起作用,因为在我输入对控制台的响应后它继续 运行 没有结束(如果重要的话,我在 repl.it 上)。阻止它结束的代码有什么问题?

public static String createSize() {
    int count = 0;
    String answer = "";
    Scanner sc = new Scanner(System.in);
    System.out.println("How big do you want the grid? (Sizes: 4x4, 5x5, 6x6)");
    String size = sc.nextLine();
    //Checks if user-inputted answer matches possible answers
    while (count < 1) {
      if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
        count++;
        answer = sc.nextLine();
      }
      else {
        System.out.println("That was not a viable size. Please type a viable size.");
        size = sc.nextLine();
      }
    }
    sc.close();    
    return answer;
  }

主要问题是什么?我尝试在所有可能的测试用例上 运行 这段代码,但没有遇到任何问题。

在第一个 If 中检查 while 循环 变化

answer = sc.nextLine();

answer = size;

因为您不希望用户输入两次尺寸。 您的代码现在应该可以正常工作了。

如果有任何不清楚的地方,请告诉我,以便我进一步修改和详细说明

在 if 语句中你有 answer = sc.nextLine(); 这将再次要求你输入这就是为什么程序没有进一步执行的原因。如果您仅第二次传递输入,那么它将执行。此外,在 if 语句中 answer 未分配任何值,因此即使输入两个值后也不会 return 任何值。

更正:-

if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
    count++;
    answer = size;
  }