新扫描仪不等待输入

new Scanner not waiting for input

执行时,以下代码不会等待用户输入:

  private int getInt(){
    Scanner sc = new Scanner(System.in);
    int result = 0;
    while (sc.hasNext()){
      System.out.println("There is a token");
      if (sc.hasNextInt()){
        result = sc.nextInt();
      } else {
        sc.next();
      }
    }
    System.out.println("There is not a token");
    sc.close();
    return result;
  }

我在调用另一个获取字符串而不是 int 的函数后立即调用此函数。此功能正常工作。

private String getString(String prompt, String pattern, String errorMessage){
    System.out.println(prompt);
    Scanner sc = new Scanner(System.in);
    while (!sc.hasNext(pattern)){
      System.out.println(errorMessage);
      sc.next();
      System.out.println(prompt);
    }
    String result = sc.next();
    sc.close();
    return result;
  }

我看到其他类似的问题,人们尝试连续使用多种方法读取数据,通常是 nextLine() 然后是 nextInt 并且不首先使用令牌的末尾,但我认为这不是这里发生了什么。

程序不等待用户输入,直接跳到调试行“没有令牌”。如有任何帮助,我们将不胜感激!

调用代码如下:

System.out.printf("Hello %s, you are %d and were born in %d. You are %s tall", m.getString(), m.getInt(), m.getBirthYear(), m.convertHeight(m.getHeight()));

此代码:

public class ScannerDemo {
    public static void main (String[] args) {
        ScannerDemo m = new ScannerDemo();
        Scanner sc = new Scanner(System.in);
        System.out.printf(
            "Hello %s, you are %d and were born in %d. You are %s tall",
            m.getString(sc), m.getInt(sc), m.getInt(sc), m.getString(sc));
        sc.close();
    }
    
    private int getInt (Scanner sc) {
        int result = sc.nextInt();
        return result;
    }
    
    private String getString (Scanner sc) {
        String result = sc.next();
        return result;
    }
}

当给出此输入时:

Hector
53
1968
5'8"

产生以下输出:

Hello Hector, you are 53 and were born in 1968. You are 5'8" tall

主要问题是在每个方法中调用 sc.close()。当您关闭此方法时,您实际上关闭了与 Scanner 对象关联的输入流,并且一旦关闭它,就无法重新打开它。我还删除了所有不必要的代码。您可以根据需要插入提示。