hasNextInt() and nextInt() method flow - java

How does this conditional statement (from Udacity's Intro to Java Programming | Problem Set 4 | Question #20) work?
import java.util.Scanner;
public class MonthPrinter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a month number (1 through 12) ");
if (!in.hasNextInt()) {
System.out.println("Not an integer. Terminating");
} else {
int theMonthNumber = in.nextInt();
if (!(theMonthNumber >= 1 && theMonthNumber <= 12)) {
System.out.println("Number must be 1 through 12");
} else {
Month test = new Month(theMonthNumber);
System.out.print(test.getMonthName() + " " + test.getNumberOfDays());
}
}
}
}
The first if (!in.hasNextInt()) checks to see if the user input is an integer. If it's NOT an integer, the main method prints Not an integer. Terminating. That makes complete sense.
However, in the event that the user inputs an integer, the code proceeds to the else statement where the next line of code is int theMonthNumber = in.nextInt();
When the program runs and I provide an integer as an input, I'm NOT prompted for another input. I'm thinking that both the hasNextInt() method and nextInt() method should request an input from the user. Therefore, I should be prompted for a total of two inputs (assuming I provide an integer). When I dry-run this scenario, I input an integer 3. This passes the if(!hasNextInt()) check.
What am I missing in the logical flow of the statement(s)?

I'm thinking in my mind that both the hasNextInt() method and nextInt() method should request an input from the user.
No. The Scanner.hasNextInt() Javadoc says (in part)
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
The last sentence is telling you that it does not consume the int.

Function hasNextInt() is just for checking the input value. It will not consume the input. What happens is, it will advance the Scanner and check the data but after that it will go back to it's previous position. So technically, the position of Scanner has not changed. That's why it's not prompting for next input.
Only nextInt() will consume the data. Scanner will advance to the next position after calling this function.

Related

While-loop will not terminate in console after entering numbers

I keep trying to get this to work but when I enter in the numbers and enter them into the console it does not finish. I have to terminate myself.
import java.util.Scanner;
public static void main(String[] args) {
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (keyboard.hasNextInt());
System.out.println(outputSum);
}
Well, yes. The keyboard.hasNextInt() call will return false for two reasons.
The next token is a NOT an integer.
You have reached the end-of-input.
What is (most likely) happening is that you have stopped entering numbers. The program is (patiently) waiting for you to enter ... something.
Solutions:
Tell the user to enter the (OS specific) terminal "end of file" character. On Linux it is CTRL-D. On Windows CTRL-Z.
Tell the user to enter something that isn't an integer.
Pick an integer as meaning that there are no more numbers, and test for that.
You also need to instruct the user how to "end" the sequence; e.g.
System.out.println("Enter sequence of numbers. Enter a non-number to stop.");
This is actually a problem with your application's "user interface" design. If the user is expected to type an arbitrarily long sequence of numbers (or something else), then there needs to be some way for the user to tell the program that the sequence is finished. The program cannot magically distinguish the cases of "there are no more" and "hang on, I'm taking a break from typing".
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
In this case hasNext() won't return true because there is neither any integer nor any whitespace. Therefore the program waits for the next input. Besides use a specific integer to break the loop.
for instance,
System.out.println("Input -1 will end the program!";
do{
int x = keyboard.nextInt();
if(x == -1){
break;
}
//do something
}while(true);
Your code is ok. There is no issue.
But before writing code, we need to think about it. The workflow of your code below:
1st time when we enter do loop, keyboard.nextInt() takes input from us.
Then it calculates the sum and performs string operation.
After that, while's keyboard.hasNextInt() takes next input from you.
Checks your input. If your input is not an integer, while loop will terminate(break).
If your input is an integer then, code loop back to keyboard.nextInt(). But this time, it does not take input from you.
It pases the buffered input(keyboard.hasNextInt()) to keyboard.nextInt() and assign the value to inputNum
So, when you want to terminate while loop, you should input any character like a, b, c, etc.
You haven't specified when the loop will end. Have a condition such as inputting a certain number that will end the program once entered, as currently your program is just going to wait for more input. Something like :
System.out.println("Enter sequence of numbers to add. Enter '0' to end the program");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (inputNum != 0);//Keeps going as long as 0 is not entered
//When zero is entered, program shows the total sum and terminates
if (inputNum == 0) {
System.out.println("The sum of all total numbers: ");
System.out.println(outputSum);
System.exit(0);//Terminates program
}
Basic syntax of do-while Loop:
do{
// do something
}while(terminating condition);
If you are using hasNextInt() method of Scanner object for terminating condition in do-while loop then loop will be terminated once it get input other than an integer value (e.g float, double, char, String etc.. ) as shown in below complete program.
import java.util.Scanner;
public class Cumulative{
public static void main(String[] args){
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do{
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
}while (keyboard.hasNextInt()); // loop will terminated whenever get any value other than valid integer such as float char or String etc..
System.out.println(outputSum);
}
}

hasNextInt won't return false and exit the loop

I'm trying to put user input into an array but the hasNextInt() method will not return false and stop the input.
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int target = in.nextInt();
while(in.hasNextInt()) {
weights.insert(in.nextInt());
}
recKnapSack(target, 0);
}
Scanner.hasNextInt() will return false when it encounters a non-integer character in its buffer.
However, it may strip out whitespace when it's reading prompts. So Space+Enter or Enter will most likely not stop the loop. But any other character will.
Since you'd like to input any number of ints, you must instruct the user on what to type when they're done. In fact, if you're writing a console application, it's a good idea to always explain WHY a program is waiting for input.
Any non-integer will stop the loop condition. In this case the syntax will work as-is, the user just needs some instruction:
System.out.println("Please enter the target");
int target = in.nextInt();
System.out.println("Enter weights. Type 'X' to stop");
while(in.hasNextInt()) {

Scanner#nextLine() leaves a leftover newline character

I've been running into a problem with Scanner#nextLine. From my understanding, nextLine() should return the rest of the current input stream and then move on to the next line.
while (true){
try{
System.out.println("Please enter a month in numeric form");
month = input.nextInt();
System.out.println("Please enter a day in numeric form");
day = input.nextInt();
System.out.println("Please enter a two-digit year");
if (input.hasNextInt() == true){
year = input.next();
}
else{
throw new java.util.InputMismatchException();
}
break;
}
catch(Exception e){
System.err.println(e);
System.out.println("\nOne of your inputs was not valid.");
System.out.println(input.nextLine());
}
}
The problem is the last line. If I leave it as input.nextLine(), the next iteration of the loop accepts a newline character for the month. Why is that? Shouldn't the call to nextLine in the catch block consume the rest of the line (including the newline) and prompt the user correctly in the next iteration? Note: I've decided to print them to try and figure out what's happening, but no cigar.
I've gathered some output from the terminal to illustrate what I mean:
// What should happen (this is when catch contains input.next() rather than nextLine)
/*
Please enter a month in numeric form
8
Please enter a day in numeric form
2
Please enter a two-digit year
badinput
java.util.InputMismatchException
One of your inputs was not valid.
badinput
Please enter a month in numeric form <------------- prompts for input, as expected
*/
// What happens when I have nextLine in the catch block (code above)
/*
Please enter a month in numeric form
8
Please enter a day in numeric form
2
Please enter a two-digit year
badinput
java.util.InputMismatchException
One of your inputs was not valid.
<------------ leftover newline printed, as expected
Please enter a month in numeric form <---------------- does not prompt for input due to another leftover newline (why?)
java.util.InputMismatchException
One of your inputs was not valid.
badinput <----------------------- prints badinput even though it should've been consumed on the last iteration (why?)
Please enter a month in numeric form
*/
Before someone marks this as a duplicate, please understand that I've looked at the differences between next and nextLine on stackoverflow already. nextLine should consume the newline character but it doesn't seem to do that here. Thanks.
if (input.hasNextInt() == true) { // prefer `if(input.hasNextInt())`
year = input.next();
} else {
throw new java.util.InputMismatchException();
}
for input badinput will evaluate input.hasNextInt() as false which means that else block will be executed without consuming that badinput (to do it we need to call next() - not nextLine() because as you probably know if we use nextLine after nextInt we will consume remaining line separator, not value from next like, more info at Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods).
So since else block simply throws exception it moves control flow to catch section. This means we are skipping break so our loop will need to iterate once again.
Now in catch section you are simply printing
System.err.println(e);
System.out.println("\nOne of your inputs was not valid.");
System.out.println(input.nextLine());
which prints exception e, string "\nOne of your inputs was not valid." and result of nextLine() (which as explained before) will simply consume line separators which remained after last nextInt() call, so we still didn't consume badinput from Scanner.
This means that when loop starts another iteration and asks for month, it receives batinput which is not valid int so nextInt() throws InputMismatchException. And again we end up in catch block and we call nextLine() which this time consumes badinput.
Now since we finally consumed that incorrect value loop will start another iteration and we will be asked for value for month.
To avoid this kind of problems please read examples from: Validating input using java.util.Scanner. In first example you will find way to validate each input at time it is provided
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
To avoid writing this code many times create your own utility method. You can even skip condition where you require from number to be positive like:
public static int getInt(Scanner sc, String askMsg) {
System.out.println(askMsg);
while (!sc.hasNextInt()) {
System.out.println("That's not a number. Please try again");
sc.next(); // consuming incorrect token
}
//here we know that next value is proper int so we can safely
//read and return it
return sc.nextInt();
}
With this method your code could be reduced to
Scanner input = new Scanner(System.in);
int month = getInt(input, "Please enter a month in numeric form");
int day = getInt(input, "Please enter a day in numeric form");
int year = getInt(input, "Please enter a two-digit year");
You can add another version of that utility method in which you can let programmer add conditions which number should pass. We can use IntPredicate functional interface for that added in Java 8, which will allow us to create conditions using lambdas like
public static int getInt(Scanner sc, String askMsg, IntPredicate predicate) {
System.out.println(askMsg);
int number;
boolean isIncorrect = true;
do {
while (!sc.hasNextInt()) {
String value = sc.next(); // consuming incorrect token
System.out.println(value + " is not valid number. Please try again");
}
number = sc.nextInt();
if (!predicate.test(number)) {
System.out.println(number + " is not valid number. Please try again");
}else{
isIncorrect=false;
}
} while (isIncorrect);
return number;
}
Usage:
int year = getInt(input, "Please enter a two-digit year", i -> (i>=10 && i<=99));
I suspect when you are entering two digit year, and as you are using next() to read it so it will read the next string only. And it will leave 2 to be read by your nextLine() new line or empty value before even you enter the value for your 2 digit year and anything after that will be left over including the new line or carriage return as you entered an invalid value. So your nextLine() inside catch just reads that left over part of invalid input but leaves the new line or carriage return as is. which is causing the exception to occur while you expect prompt to appear to read month. you can place nextLine() after each nextInt() or next() to resolve the issue.
Remember, the Scanner does not see your print statements, it just reads input as a stream of characters. The fact that you, as a user, enter those characters one line at a time is meaningless to the scanner.
So, you type 8<ENTER> (where <ENTER> represents that actual newline character(s) of your OS). After nextInt(), the 8 has been consumed.
You then type 2<ENTER>, making the pending input <ENTER>2<ENTER>. Remember, only the 8 was consumed, so far. nextInt() skips then whitespace and returns 2, thereby consuming <ENTER>2.
You then type badinput<ENTER>, making the pending input <ENTER>badinput<ENTER>. Since the next token is not a valid integer number, you throw exception, and enter the catch block, where you call nextLine(). It consumes all character up to and including the first <ENTER>, and returns the text before, i.e. an empty string.
At this point in time, badinput<ENTER> is still pending in the stream, and is processed when you loop back.
This is one of the main flaws in how people use Scanner. nextInt() doesn't consume the line, only the token, leaving the rest of the line behind.
Example of how things go bad with Scanner:
Please enter a month in numeric form
8 2 17
Please enter a day in numeric form
Please enter a two-digit year
Because user entered all 3 values on the first line, you code will get the values, but will still print the next two prompts, even though that is unnecessary. It's just weird like that.
Solution 1: Don't use Scanner. It's just too dang weird. Too easy to use, and soooo easy to misuse, aka soooo difficult to use correctly.
Solution 2: Call nextLine() after each nextInt() to flush (silently consume) any extra text after the accepted value. If you do that, the example would go like this:
Please enter a month in numeric form
8 2 17
Please enter a day in numeric form
2
Please enter a two-digit year
17
The <SPACE>2<SPACE>17<ENTER> on the first line would be silently ignored.
You could extend the logic to if (! nextLine().trim().isEmpty()) {/*ERROR*/} if you want full error handling.

Continuing to be Able to Input with Scanner

Why is it that, in the code below, you are able to continuously enter numbers into the scanner? I feel the code would cause an infinite loop upon entering a double because
userInput.hasNextDouble()
would always be true, since the value of userInput doesn't change throughout the loop.
I would like an explanation as to why the while condition does not cause an infinite loop.
public class Testing
{
public static void main(String[] args)
{
System.out.println("Enter numbers: ");
Scanner userInput = new Scanner(System.in);
int currentSize = 0;
while (userInput.hasNextDouble())
{
double nextScore = userInput.nextDouble();
currentSize++;
}
System.out.println(currentSize);
}
}
The scanner class basically scans over tokens entered into the input stream. When you call a hasNextDouble() or any hasNext method it will attempt to look at the next token in the stream. It will wait until a token exists before returning the value, then calling nextDouble() will take that token and clear it from the stream so when you get back to hasNextDouble() it is going to wait until you enter another token into the stream.
hasNextDouble() is a method to indicate whether or not a double has been entered. If, in that code, the user enters something other than a double, for instance a char or boolean, the code will break out of the loop and print currentSize. A better thing to do would be like this:
System.out.println("Enter numbers: ");
Scanner userInput = new Scanner(System.in);
int currentSize = 0;
char choice = 'c';
while (choice != 't')
{
double nextScore = userInput.nextDouble();
currentSize++;
System.out.println("Enter \"c\" to enter more numbers, or \"t\" to exit.");
choice = userInput.nextChar();
}
System.out.println(currentSize);
}
From the javadoc of Scanner
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
So if you don't enter a double, you immediately come out of that while loop.

Java: Infinite loop using Scanner in.hasNextInt()

I am using the following code:
while (invalidInput)
{
// ask the user to specify a number to update the times by
System.out.print("Specify an integer between 0 and 5: ");
if (in.hasNextInt())
{
// get the update value
updateValue = in.nextInt();
// check to see if it was within range
if (updateValue >= 0 && updateValue <= 5)
{
invalidInput = false;
}
else
{
System.out.println("You have not entered a number between 0 and 5. Try again.");
}
} else
{
System.out.println("You have entered an invalid input. Try again.");
}
}
However, if I enter a 'w' it will tell me "You have entered invalid input. Try Again." and then it will go into an infinite loop showing the text "Specify an integer between 0 and 5: You have entered an invalid input. Try again."
Why is this happening? Isn't the program supposed to wait for the user to input and press enter each time it reaches the statement:
if (in.hasNextInt())
In your last else block, you need to clear the 'w' or other invalid input from the Scanner. You can do this by calling next() on the Scanner and ignoring its return value to throw away that invalid input, as follows:
else
{
System.out.println("You have entered an invalid input. Try again.");
in.next();
}
The problem was that you did not advance the Scanner past the problematic input. From hasNextInt() documentation:
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
This is true of all hasNextXXX() methods: they return true or false, without advancing the Scanner.
Here's a snippet to illustrate the problem:
String input = "1 2 3 oops 4 5 6";
Scanner sc = new Scanner(input);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
int num = sc.nextInt();
System.out.println("Got " + num);
} else {
System.out.println("int, please!");
//sc.next(); // uncomment to fix!
}
}
You will find that this program will go into an infinite loop, asking int, please! repeatedly.
If you uncomment the sc.next() statement, then it will make the Scanner go past the token that fails hasNextInt(). The program would then print:
Got 1
Got 2
Got 3
int, please!
Got 4
Got 5
Got 6
The fact that a failed hasNextXXX() check doesn't skip the input is intentional: it allows you to perform additional checks on that token if necessary. Here's an example to illustrate:
String input = " 1 true foo 2 false bar 3 ";
Scanner sc = new Scanner(input);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
System.out.println("(int) " + sc.nextInt());
} else if (sc.hasNextBoolean()) {
System.out.println("(boolean) " + sc.nextBoolean());
} else {
System.out.println(sc.next());
}
}
If you run this program, it will output the following:
(int) 1
(boolean) true
foo
(int) 2
(boolean) false
bar
(int) 3
This statement by Ben S. about the non-blocking call is false:
Also, hasNextInt() does not block. It's the non-blocking check to see if a future next call could get input without blocking.
...although I do recognize that the documentation can easily be misread to give this opinion, and the name itself implies it is to be used for this purpose. The relevant quote, with emphasis added:
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
It is a subtle point, to be sure. Either saying "Both the hasNext and next methods", or "Both hasnext() and next()" would have implied that the companion methods would act differently. But seeing as they conform to the same naming convention (and the documentation, of course), it's reasonable to expect they act the same, and hasNext()
clearly says that it can block.
Meta note: this should probably be a comment to the incorrect post, but it seems that as a new user I can only post this answer (or edit the wiki which seems to be preferred for sytlistic changes, not those of substance).
Flag variables are too error prone to use. Use explicit loop control with comments instead. Also, hasNextInt() does not block. It's the non-blocking check to see if a future next call could get input without blocking. If you want to block, use the nextInt() method.
// Scanner that will read the integer
final Scanner in = new Scanner(System.in);
int inputInt;
do { // Loop until we have correct input
System.out.print("Specify an integer between 0 and 5: ");
try {
inputInt = in.nextInt(); // Blocks for user input
if (inputInt >= 0 && inputInt <= 5) {
break; // Got valid input, stop looping
} else {
System.out.println("You have not entered a number between 0 and 5. Try again.");
continue; // restart loop, wrong number
}
} catch (final InputMismatchException e) {
System.out.println("You have entered an invalid input. Try again.");
in.next(); // discard non-int input
continue; // restart loop, didn't get an integer input
}
} while (true);

Categories

Resources