finlander
finlander

Reputation: 1

java hasNext method for checking scanner for more tokens

I'd like to use the snippet of code below to allow a user to enter four values at once separated by spaces, in which case they would be captured separately and assigned to variables. Alternatively, the user could enter one value at a time while waiting for prompts between each value. If the if(in.hasNext()) worked like I had hoped, this solution would have been easily doable with the code below, but I have learned that hasNext is apparently always evaluating to TRUE, even when there is no additional token in the stream, so the program blocks and waits for input. Is there a way to adjust this code to get the desired results? (month, day, and year are strings that get parsed to integers later in the program.) Thanks

Scanner in = new Scanner(System.in); 
System.out.println("Please enter your first name, last name, or full name:"); 
traveler = in.nextLine();

System.out.println("Please enter your weight, birth month, birth day of month, and birth year as numbers.\nYou may enter all the numbers at once -- right now -- or you may enter them one at a time as the prompts appear.\nOr, you may also enter them in any combination at any time, so long as weight (at least) is entered now and the remaining \nthree numbers are eventually entered in their correct order:");
pounds = in.nextInt();

if (in.hasNext()) {
    month = in.next(); 
} else {
    System.out.println("Please enter your birth month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth month:");
    month = in.next(); 
  }
if (in.hasNext()) {
    day = in.next();
} else {
    System.out.println("Please enter your birth day of month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth day of month:");
    day = in.next(); 
  } 
if (in.hasNext()) {
    year = in.next();
} else {
    System.out.println("If you've made it this far, then please just enter your birth year:");
    year = in.next(); 
  }

Upvotes: 0

Views: 2138

Answers (2)

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

There is a InputStream.available() method that returns how many characters can be read without blocking; however, that does not determine whether there is a complete number or line. The Scanner class's documentation explicitly says that hasNext can block, though.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234807

Read a line at a time, then call split(" ") to determine how many and which values the user entered.

Upvotes: 1

Related Questions