'new Scanner not waiting for input

When executed, the following code will not wait for user 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;
  }

I am calling this function immediately after calling another functions that gets a string rather than an int. This functions works correctly.

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;
  }

I have seen other similar questions where people try to read in data using multiple methods in succession, normally nextLine() then nextInt and don't consume the end of the token first, but I don't think this is what's happening here.

The programme doesn't wait for user input and just skips straight to the debugging line "There is not a token". Any help would be appreciated!

The calling code is as follows:

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()));


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source