LucasGracia
LucasGracia

Reputation: 125

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

Upvotes: 0

Views: 65

Answers (1)

hfontanez
hfontanez

Reputation: 6168

This code:

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

When given this input:

Hector
53
1968
5'8"

Produces the following output:

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

The main problem is calling sc.close() inside each method. When you close this method, you actually close the input stream associated with the Scanner object and once you close it, there is no way to reopen it. I also took out all unnecessary code. You can insert the prompts as needed.

Upvotes: 1

Related Questions