How does input.nextInt() work exactly? - java

This is the program
public class bInputMismathcExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.println("Enter an integer:");
int num = input.nextInt();
System.out.println("the number is " + num);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (Incorrect input: an integer is required)");
}
input.nextLine();
}
while (continueInput);
}
}
I know nextInt() only read the integer not the "\n", but why should we need the input.nextLine() to read the "\n"? is it necessary?? because I think even without input.nextLine(), after it goes back to try {}, the input.nextInt() can still read the next integer I type, but in fact it is a infinite loop.
I still don't know the logic behind it, hope someone can help me.

The reason it is necessary here is because of what happens when the input fails.
For example, try removing the input.nextLine() part, run the program again, and when it asks for input, enter abc and press Return
The result will be an infinite loop. Why?
Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared. It will still be abc in the buffer. So going back to the loop will cause it to try parsing the same abc over and over.
Using nextLine() will clear the buffer, so that the next input you read after an error is going to be the fresh input that's after the bad line you have entered.

but why should we need the input.nextLine() to read the "\n"? is it necessary??
Yes (actually it's very common to do that), otherwise how will you consume the remaining \n? If you don't want to use nextLine to consume the left \n, use a different scanner object (I don't recommend this):
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
input1.nextInt();
input2.nextLine();
or use nextLine to read the integer value and convert it to int later so you won't have to consume the new line character later.

Also you can use:
input.nextInt();
input.skip("\\W*").nextLine();
or
input.skip("\n").nextLine();
if you need whitespaces before line

Related

clearing a Char buffer from a scanner input [duplicate]

I have something like this:
Scanner in=new Scanner(System.in);
int rounds = 0;
while (rounds < 1 || rounds > 3) {
System.out.print("How many rounds? ");
if (in.hasNextInt()) {
rounds = in.nextInt();
} else {
System.out.println("Invalid input. Please try again.");
System.out.println();
}
// Clear buffer
}
System.out.print(rounds+" rounds.");
How can I clear the buffer?
Edit: I tried the following, but it does not work for some reason:
while(in.hasNext())
in.next();
Try this:
in.nextLine();
This advances the Scanner to the next line.
You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.
Use the following command:
in.nextLine();
right after
System.out.println("Invalid input. Please Try Again.");
System.out.println();
or after the following curly bracket (where your comment regarding it, is).
This command advances the scanner to the next line (when reading from a file or string, this simply reads the next line), thus essentially flushing it, in this case. It clears the buffer and readies the scanner for a new input. It can, preferably, be used for clearing the current buffer when a user has entered an invalid input (such as a letter when asked for a number).
Documentation of the method can be found here:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
Hope this helps!
This should fix it...
Scanner in=new Scanner(System.in);
int rounds = 0;
while (rounds < 1 || rounds > 3) {
System.out.print("How many rounds? ");
if (in.hasNextInt()) {
rounds = in.nextInt();
} else {
System.out.println("Invalid input. Please try again.");
in.next(); // -->important
System.out.println();
}
// Clear buffer
}
System.out.print(rounds+" rounds.");
Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.
You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.
in = new Scanner(System.in);
If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.
(The above approach is specific to System.in. It might not be appropriate for other input streams.)
If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.
scan.nextLine();
Put the above line before reading String input

Try Catch Exception stuck repeating in any while loop (Java) [duplicate]

This is the program
public class bInputMismathcExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.println("Enter an integer:");
int num = input.nextInt();
System.out.println("the number is " + num);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (Incorrect input: an integer is required)");
}
input.nextLine();
}
while (continueInput);
}
}
I know nextInt() only read the integer not the "\n", but why should we need the input.nextLine() to read the "\n"? is it necessary?? because I think even without input.nextLine(), after it goes back to try {}, the input.nextInt() can still read the next integer I type, but in fact it is a infinite loop.
I still don't know the logic behind it, hope someone can help me.
The reason it is necessary here is because of what happens when the input fails.
For example, try removing the input.nextLine() part, run the program again, and when it asks for input, enter abc and press Return
The result will be an infinite loop. Why?
Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared. It will still be abc in the buffer. So going back to the loop will cause it to try parsing the same abc over and over.
Using nextLine() will clear the buffer, so that the next input you read after an error is going to be the fresh input that's after the bad line you have entered.
but why should we need the input.nextLine() to read the "\n"? is it necessary??
Yes (actually it's very common to do that), otherwise how will you consume the remaining \n? If you don't want to use nextLine to consume the left \n, use a different scanner object (I don't recommend this):
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
input1.nextInt();
input2.nextLine();
or use nextLine to read the integer value and convert it to int later so you won't have to consume the new line character later.
Also you can use:
input.nextInt();
input.skip("\\W*").nextLine();
or
input.skip("\n").nextLine();
if you need whitespaces before line

Is there an equivalent of while(scanf()==1) in java?

I have been using the following code in c and c++ for looping till user feeds the correct value till the program comes out of it:
while((scanf("%d",&num)==1)//same way in for loop
{
//some code
}
Can i some how use the same way to accept and loop the program till i keep entering let's say an integer and floating or a char or a special character breaks it.
Use :
Scanner sc = new Scanner(System.in); // OR replace System.in with file to read
while(sc.hasNext()){
//code here
int x = sc.nextInt();
//...
}
There are different variants of hasNext() for specific expected input types: hasNextFloat(), hasNextInt()..
Same goes for next() method so you can find nextInt(), nextFloat() or even nextLine()
You can go to Java doc for more info.
As proposed in comments, you can use the Scanner class.
Note you need to read the in buffer with a nextLine() when it is not an int.
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter an int: ");
while (!in.hasNextInt()) {
System.out.println("That's not an int! try again...");
in.nextLine();
}
int myInt = in.nextInt();
System.out.println("You entered "+myInt);
}
}

Try Catch keeps looping instead of asking for another value?

I have the following code:
Scanner inputSide = new Scanner(System.in);
double side[] = new double[3];
int i = 0;
do{
try{
System.out.println("Enter three side lengths for a triangle (each followed by pressing enter):");
side[i] = inputSide.nextDouble();
i++;
}
catch(Exception wrongType){
System.err.println(wrongType);
System.out.println("Please enter a number. Start again!!");
i=0;
}
}
while(i<3);
It works fine and does what it's meant to if I don't enter a wrong data type but if I enter something other than a double then it loops over and over, printing everything in both try and catch blocks instead of waiting for me to enter another double.
Any help as to why it's doing this - as I can't seem to understand why - would be appreciated.
Thank you :)
The problem is that, you have used input.nextDouble method, which reads only the next token in the input, thus skipping the newline at the end. See Scanner.nextDouble
Now, if you enter wrong value first time, then it will consider the newline as the next input. Which will also be invalid.
You can add an empty input.nextLine in the catch block.
catch(Exception wrongType){
System.err.println(wrongType);
System.out.println("Please enter a number. Start again!!");
i=0;
input.nextLine(); // So that it consumes the newline left over
}
Now, your nextLine() will read the linefeed left over, and linefeed will not be taken as input to your nextDouble next time. In which case, it will fail, even before you giving any input.

java.util.Scanner : why my nextDouble() does not prompt?

import java.util.*;
public class June16{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
double b=0;
boolean checkInput = true;
do{
try{
System.out.println("Input b : ");
b = kb.nextDouble();
checkInput = false;
}catch(InputMismatchException ime){
}
}while(checkInput);
}
}
After InputMismatchException is thrown, why my program not prompt for input? :D
From the documentation:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
This is why you end up in an infinite loop if you don't enter a valid double. When you handle the exception, move to the next token with kb.next().
Because if the Scanner.nextDouble() failes it leaves the token on the queue, (which is then read again and again causing it to fail over and over again).
Try the following:
try {
// ...
} catch (InputMismatchException ime) {
kb.next(); // eat the malformed token.
}
ideone.com demo illustrating working example
This is due to the fact that nextDouble will take the decimal number you entered, but there is still a carriage return that you enter that was not read by the scanner. The next time it loops it reads the input, but wait! there is a carriage return there, so... no need to scan anything. It just processes the carriage return. Of course, the program finds that it is not a double, so you get an exception.
How do you fix it? Well, have something that scans whatever leftovers were left by the nextDouble (namely a next()) and then scan the next double again.

Categories