Scanner is skipping nextLine() after using next() or nextFoo()?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I am using the Scanner
methods nextInt()
and nextLine()
for reading input.
It looks like this:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine()
is skipped and the second input.nextLine()
is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt()
. If I delete it, then both string1 = input.nextLine()
and string2 = input.nextLine()
are executed as I want them to be.
java io java.util.scanner
add a comment |
I am using the Scanner
methods nextInt()
and nextLine()
for reading input.
It looks like this:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine()
is skipped and the second input.nextLine()
is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt()
. If I delete it, then both string1 = input.nextLine()
and string2 = input.nextLine()
are executed as I want them to be.
java io java.util.scanner
4
Related: stackoverflow.com/questions/4708219/…
– James P.
Aug 14 '11 at 12:27
25
The newline character is probably not consumed.
– Lews Therin
Oct 27 '12 at 16:39
5
Style note: you should declare your String variables on the same line you assign a value. E.g.String string1 = input.nextLine ()
.
– Duncan Jones
Oct 27 '12 at 16:39
2
@Lews Therin: Yes, you are right. After another couple of test I found that it is executed and read "n". How to avoid of that?
– blekione
Oct 27 '12 at 16:45
3
Or you could be like me and use BufferedReader :) I don't care if it's old school, it has always worked and always will work for me. Also, knowledge of BufferedReader has application elsewhere. I simply don't like Scanner.
– Cruncher
Aug 27 '13 at 19:36
add a comment |
I am using the Scanner
methods nextInt()
and nextLine()
for reading input.
It looks like this:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine()
is skipped and the second input.nextLine()
is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt()
. If I delete it, then both string1 = input.nextLine()
and string2 = input.nextLine()
are executed as I want them to be.
java io java.util.scanner
I am using the Scanner
methods nextInt()
and nextLine()
for reading input.
It looks like this:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
The problem is that after entering the numerical value, the first input.nextLine()
is skipped and the second input.nextLine()
is executed, so that my output looks like this:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
I tested my application and it looks like the problem lies in using input.nextInt()
. If I delete it, then both string1 = input.nextLine()
and string2 = input.nextLine()
are executed as I want them to be.
java io java.util.scanner
java io java.util.scanner
edited Apr 4 '18 at 13:31
Lii
7,33244263
7,33244263
asked Oct 27 '12 at 16:37
blekioneblekione
3,18631117
3,18631117
4
Related: stackoverflow.com/questions/4708219/…
– James P.
Aug 14 '11 at 12:27
25
The newline character is probably not consumed.
– Lews Therin
Oct 27 '12 at 16:39
5
Style note: you should declare your String variables on the same line you assign a value. E.g.String string1 = input.nextLine ()
.
– Duncan Jones
Oct 27 '12 at 16:39
2
@Lews Therin: Yes, you are right. After another couple of test I found that it is executed and read "n". How to avoid of that?
– blekione
Oct 27 '12 at 16:45
3
Or you could be like me and use BufferedReader :) I don't care if it's old school, it has always worked and always will work for me. Also, knowledge of BufferedReader has application elsewhere. I simply don't like Scanner.
– Cruncher
Aug 27 '13 at 19:36
add a comment |
4
Related: stackoverflow.com/questions/4708219/…
– James P.
Aug 14 '11 at 12:27
25
The newline character is probably not consumed.
– Lews Therin
Oct 27 '12 at 16:39
5
Style note: you should declare your String variables on the same line you assign a value. E.g.String string1 = input.nextLine ()
.
– Duncan Jones
Oct 27 '12 at 16:39
2
@Lews Therin: Yes, you are right. After another couple of test I found that it is executed and read "n". How to avoid of that?
– blekione
Oct 27 '12 at 16:45
3
Or you could be like me and use BufferedReader :) I don't care if it's old school, it has always worked and always will work for me. Also, knowledge of BufferedReader has application elsewhere. I simply don't like Scanner.
– Cruncher
Aug 27 '13 at 19:36
4
4
Related: stackoverflow.com/questions/4708219/…
– James P.
Aug 14 '11 at 12:27
Related: stackoverflow.com/questions/4708219/…
– James P.
Aug 14 '11 at 12:27
25
25
The newline character is probably not consumed.
– Lews Therin
Oct 27 '12 at 16:39
The newline character is probably not consumed.
– Lews Therin
Oct 27 '12 at 16:39
5
5
Style note: you should declare your String variables on the same line you assign a value. E.g.
String string1 = input.nextLine ()
.– Duncan Jones
Oct 27 '12 at 16:39
Style note: you should declare your String variables on the same line you assign a value. E.g.
String string1 = input.nextLine ()
.– Duncan Jones
Oct 27 '12 at 16:39
2
2
@Lews Therin: Yes, you are right. After another couple of test I found that it is executed and read "n". How to avoid of that?
– blekione
Oct 27 '12 at 16:45
@Lews Therin: Yes, you are right. After another couple of test I found that it is executed and read "n". How to avoid of that?
– blekione
Oct 27 '12 at 16:45
3
3
Or you could be like me and use BufferedReader :) I don't care if it's old school, it has always worked and always will work for me. Also, knowledge of BufferedReader has application elsewhere. I simply don't like Scanner.
– Cruncher
Aug 27 '13 at 19:36
Or you could be like me and use BufferedReader :) I don't care if it's old school, it has always worked and always will work for me. Also, knowledge of BufferedReader has application elsewhere. I simply don't like Scanner.
– Cruncher
Aug 27 '13 at 19:36
add a comment |
15 Answers
15
active
oldest
votes
That's because the Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine
returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer usingInteger.parseInt(String)
method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
3
@blekione. You have to usetry-catch
, becauseInteger.parseInt
throwsNumberFormatException
when an invalid argument is passed to it. You will learn about exception later on. For E.G: -Integer.parseInt("abc")
. You don't want "abc" to get converted to int right?
– Rohit Jain
Oct 27 '12 at 18:02
3
@blekione. So, in the above case, your code will halt at that point, and you won't be able to continue the execution. With Exception Handling, you can handle such kind of conditions.
– Rohit Jain
Oct 27 '12 at 18:02
4
To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.
– Mordechai
Jan 11 '17 at 3:00
2
I personally prefer aScanner#hasNextFoo
check beforehand instead of a try-catch, but that works too.
– MildlyMilquetoast
Jan 22 '17 at 1:13
1
Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).
– olmerg
Oct 24 '17 at 21:58
|
show 4 more comments
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
umm seems a solution, making the skipped line non-usednextLine
, but I still need an explanation of this behaviour
– Eng.Fouad
Aug 14 '11 at 12:25
2
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:11
add a comment |
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". When input.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine()
immediately after input.nextInt()
Mmm, that bug was corrected in now a days?
– Victor
May 29 '14 at 13:28
7
@Victor it's not bug. it's working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.
– Bohemian♦
May 29 '14 at 13:38
I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this "issue" in the next JCP.
– Victor
May 29 '14 at 14:55
@victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.
– Bohemian♦
May 29 '14 at 15:18
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
There seem to be many questions about this issue with java.util.Scanner
. I think a more readable/idiomatic solution would be to call scanner.skip("[rn]+")
to drop any newline characters after calling nextInt()
.
EDIT: as @PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
I know what we do to remove the data in buffer, but this case, please help me with this: stackoverflow.com/questions/33585314/having-issues-with-scanner
– Khuong
Nov 7 '15 at 18:03
FYI, this will cause an infinite loop is the user types any tabs or spaces after the numeric input. See my answer here for a better skip: stackoverflow.com/a/42471816/7098259
– Patrick Parker
Feb 26 '17 at 17:52
@PatrickParker: it does indeed cause an infinite loop! Thanks, edited the answer to link to yours.
– Denis Tulskiy
Feb 27 '17 at 5:57
@PatrickParker Why does is cause infinite loop ?
– Piyush
Aug 19 '17 at 8:41
add a comment |
It does that because input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding an input.nextLine();
underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
you have to use try catch here. What will happen if the input is not a number. NumberFormatException need to be handled here.
– Arundev
Mar 25 at 11:46
add a comment |
Things you need to know:
text which represents few lines also contains non-printable characters between lines (we call them line separators) like
- carriage return (CR - in String literals represented as
"r"
) - line feed (LF - in String literals represented as
"n"
)
- carriage return (CR - in String literals represented as
when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by
System.in
which is read byScanner
) also sends OS dependant line separators (like for Windowsrn
) after it.
So when you are asking the user for value like
age
, and user types 42 and presses enter, standard input will contain"42rn"
.
Problem
Scanner#nextInt
(and other Scanner#nextType
methods) doesn't allow Scanner to consume these line separators. It will read them from System.in
(how else Scanner would know that there are no more digits from the user which represent age
value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.
Now Scanner#nextLine()
simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine
also consumes those line separators.
Solution
So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine
, either
- consume line separator left by
nextInt
from Scanners cache by
- calling
nextLine
, - or by calling
skip("\R")
to let Scanner skip part matched byR
which represents line separator (more info aboutR
: https://stackoverflow.com/a/31060125)
- calling
- don't use
nextInt
(nornext
, or anynextTYPE
methods) at all. Instead read entire data line-by-line usingnextLine
and parse numbers from each line (assuming one line contains only one number) to proper type likeint
viaInteger.parseInt
.
BTW: Scanner#nextType
methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42rnrn321rnrnrnfoobar"
code
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
will be able to properly assign num1=42
num2=321
name=foobar
.
add a comment |
Instead of input.nextLine()
use input.next()
, that should solve the problem.
Modified code:
public static Scanner input = new Scanner(System.in);
public static void main(String args)
{
System.out.print("Insert a number: ");
int number = input.nextInt();
System.out.print("Text1: ");
String text1 = input.next();
System.out.print("Text2: ");
String text2 = input.next();
}
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
In order to avoid the issue, use nextLine();
immediately after nextInt();
as it helps in clearing out the buffer. When you press ENTER
the nextInt();
does not capture the new line and hence, skips the Scanner
code later.
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer
add a comment |
If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .
Code :
class ScanReader {
/**
* @author Nikunj Khokhar
*/
private byte buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}
public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == 'n' || n == 'r' || n == 't' || n == -1) return true;
else return false;
}
public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public void scanLong(long A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}
public void scanInt(int A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}
}
Advantages :
- Scans Input faster than BufferReader
- Reduces Time Complexity
- Flushes Buffer for every next input
Methods :
- scanChar() - scan single character
- scanInt() - scan Integer value
- scanLong() - scan Long value
- scanString() - scan String value
- scanDouble() - scan Double value
- scanInt(int array) - scans complete Array(Integer)
- scanLong(long array) - scans complete Array(Long)
Usage :
- Copy the Given Code below your java code.
- Initialise Object for Given Class
ScanReader sc = new ScanReader(System.in);
3. Import necessary Classes :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4. Throw IOException from your main method to handle Exception
5. Use Provided Methods.
6. Enjoy
Example :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
ScanReader sc = new ScanReader(System.in);
int a=sc.scanInt();
System.out.println(a);
}
}
class ScanReader....
add a comment |
If you want to read both strings and ints, a solution is to use two Scanners:
Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);
intScanner.close();
stringScanner.close();
add a comment |
sc.nextLine()
is better as compared to parsing the input.
Because performance wise it will be good.
add a comment |
I guess I'm pretty late to the party..
As previously stated, calling input.nextLine()
after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1
. I'll just shed a little more light to the entire topic.
Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
If we input the value below (as a single line of input)
54 234
The value of our firstNumber
and secondNumber
variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().
nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".
Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.
I hope this helps.. Merry coding!
what is a "new line feed"?
– Abcd
Jan 13 at 16:22
@Abcd A new line feed basically means 'starting from a new line'.
– Taslim Oseni
Jan 13 at 19:35
add a comment |
public static void main(String args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
– Neeraj Gahlawat
Jul 30 '17 at 3:50
add a comment |
Use 2 scanner objects instead of one
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
add a comment |
Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.
int i = new Scanner(System.in).nextInt();
1
But then you have to close theScanner
to prevent memory leak. Wasting time?
– TheCoffeeCup
Oct 8 '15 at 1:22
Doesn't the GC take care of that if the Scanner is wrapped in a method? Like: String getInput() {return new Scanner(System.in).nextLine()};
– Tobias Johansson
Jun 1 '16 at 22:14
This is absolutely incorrect.nextInt()
won't consume the newline, regardless of whether it's in a "new"Scanner
or an already used one.
– Dawood ibn Kareem
Dec 29 '16 at 20:55
add a comment |
protected by Aniket Thakur Apr 19 '15 at 9:05
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
That's because the Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine
returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer usingInteger.parseInt(String)
method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
3
@blekione. You have to usetry-catch
, becauseInteger.parseInt
throwsNumberFormatException
when an invalid argument is passed to it. You will learn about exception later on. For E.G: -Integer.parseInt("abc")
. You don't want "abc" to get converted to int right?
– Rohit Jain
Oct 27 '12 at 18:02
3
@blekione. So, in the above case, your code will halt at that point, and you won't be able to continue the execution. With Exception Handling, you can handle such kind of conditions.
– Rohit Jain
Oct 27 '12 at 18:02
4
To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.
– Mordechai
Jan 11 '17 at 3:00
2
I personally prefer aScanner#hasNextFoo
check beforehand instead of a try-catch, but that works too.
– MildlyMilquetoast
Jan 22 '17 at 1:13
1
Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).
– olmerg
Oct 24 '17 at 21:58
|
show 4 more comments
That's because the Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine
returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer usingInteger.parseInt(String)
method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
3
@blekione. You have to usetry-catch
, becauseInteger.parseInt
throwsNumberFormatException
when an invalid argument is passed to it. You will learn about exception later on. For E.G: -Integer.parseInt("abc")
. You don't want "abc" to get converted to int right?
– Rohit Jain
Oct 27 '12 at 18:02
3
@blekione. So, in the above case, your code will halt at that point, and you won't be able to continue the execution. With Exception Handling, you can handle such kind of conditions.
– Rohit Jain
Oct 27 '12 at 18:02
4
To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.
– Mordechai
Jan 11 '17 at 3:00
2
I personally prefer aScanner#hasNextFoo
check beforehand instead of a try-catch, but that works too.
– MildlyMilquetoast
Jan 22 '17 at 1:13
1
Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).
– olmerg
Oct 24 '17 at 21:58
|
show 4 more comments
That's because the Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine
returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer usingInteger.parseInt(String)
method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
That's because the Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine
returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer usingInteger.parseInt(String)
method.
int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
edited Oct 31 '18 at 1:31
TechnicallyTrue
233
233
answered Oct 27 '12 at 16:39
Rohit JainRohit Jain
169k35320448
169k35320448
3
@blekione. You have to usetry-catch
, becauseInteger.parseInt
throwsNumberFormatException
when an invalid argument is passed to it. You will learn about exception later on. For E.G: -Integer.parseInt("abc")
. You don't want "abc" to get converted to int right?
– Rohit Jain
Oct 27 '12 at 18:02
3
@blekione. So, in the above case, your code will halt at that point, and you won't be able to continue the execution. With Exception Handling, you can handle such kind of conditions.
– Rohit Jain
Oct 27 '12 at 18:02
4
To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.
– Mordechai
Jan 11 '17 at 3:00
2
I personally prefer aScanner#hasNextFoo
check beforehand instead of a try-catch, but that works too.
– MildlyMilquetoast
Jan 22 '17 at 1:13
1
Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).
– olmerg
Oct 24 '17 at 21:58
|
show 4 more comments
3
@blekione. You have to usetry-catch
, becauseInteger.parseInt
throwsNumberFormatException
when an invalid argument is passed to it. You will learn about exception later on. For E.G: -Integer.parseInt("abc")
. You don't want "abc" to get converted to int right?
– Rohit Jain
Oct 27 '12 at 18:02
3
@blekione. So, in the above case, your code will halt at that point, and you won't be able to continue the execution. With Exception Handling, you can handle such kind of conditions.
– Rohit Jain
Oct 27 '12 at 18:02
4
To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.
– Mordechai
Jan 11 '17 at 3:00
2
I personally prefer aScanner#hasNextFoo
check beforehand instead of a try-catch, but that works too.
– MildlyMilquetoast
Jan 22 '17 at 1:13
1
Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).
– olmerg
Oct 24 '17 at 21:58
3
3
@blekione. You have to use
try-catch
, because Integer.parseInt
throws NumberFormatException
when an invalid argument is passed to it. You will learn about exception later on. For E.G: - Integer.parseInt("abc")
. You don't want "abc" to get converted to int right?– Rohit Jain
Oct 27 '12 at 18:02
@blekione. You have to use
try-catch
, because Integer.parseInt
throws NumberFormatException
when an invalid argument is passed to it. You will learn about exception later on. For E.G: - Integer.parseInt("abc")
. You don't want "abc" to get converted to int right?– Rohit Jain
Oct 27 '12 at 18:02
3
3
@blekione. So, in the above case, your code will halt at that point, and you won't be able to continue the execution. With Exception Handling, you can handle such kind of conditions.
– Rohit Jain
Oct 27 '12 at 18:02
@blekione. So, in the above case, your code will halt at that point, and you won't be able to continue the execution. With Exception Handling, you can handle such kind of conditions.
– Rohit Jain
Oct 27 '12 at 18:02
4
4
To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.
– Mordechai
Jan 11 '17 at 3:00
To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.
– Mordechai
Jan 11 '17 at 3:00
2
2
I personally prefer a
Scanner#hasNextFoo
check beforehand instead of a try-catch, but that works too.– MildlyMilquetoast
Jan 22 '17 at 1:13
I personally prefer a
Scanner#hasNextFoo
check beforehand instead of a try-catch, but that works too.– MildlyMilquetoast
Jan 22 '17 at 1:13
1
1
Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).
– olmerg
Oct 24 '17 at 21:58
Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).
– olmerg
Oct 24 '17 at 21:58
|
show 4 more comments
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
umm seems a solution, making the skipped line non-usednextLine
, but I still need an explanation of this behaviour
– Eng.Fouad
Aug 14 '11 at 12:25
2
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:11
add a comment |
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
umm seems a solution, making the skipped line non-usednextLine
, but I still need an explanation of this behaviour
– Eng.Fouad
Aug 14 '11 at 12:25
2
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:11
add a comment |
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
edited Dec 29 '17 at 6:57
Ebony Maw
316516
316516
answered Aug 14 '11 at 12:24
PrinePrine
8,78073355
8,78073355
umm seems a solution, making the skipped line non-usednextLine
, but I still need an explanation of this behaviour
– Eng.Fouad
Aug 14 '11 at 12:25
2
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:11
add a comment |
umm seems a solution, making the skipped line non-usednextLine
, but I still need an explanation of this behaviour
– Eng.Fouad
Aug 14 '11 at 12:25
2
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:11
umm seems a solution, making the skipped line non-used
nextLine
, but I still need an explanation of this behaviour– Eng.Fouad
Aug 14 '11 at 12:25
umm seems a solution, making the skipped line non-used
nextLine
, but I still need an explanation of this behaviour– Eng.Fouad
Aug 14 '11 at 12:25
2
2
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:11
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:11
add a comment |
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". When input.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine()
immediately after input.nextInt()
Mmm, that bug was corrected in now a days?
– Victor
May 29 '14 at 13:28
7
@Victor it's not bug. it's working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.
– Bohemian♦
May 29 '14 at 13:38
I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this "issue" in the next JCP.
– Victor
May 29 '14 at 14:55
@victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.
– Bohemian♦
May 29 '14 at 15:18
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". When input.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine()
immediately after input.nextInt()
Mmm, that bug was corrected in now a days?
– Victor
May 29 '14 at 13:28
7
@Victor it's not bug. it's working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.
– Bohemian♦
May 29 '14 at 13:38
I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this "issue" in the next JCP.
– Victor
May 29 '14 at 14:55
@victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.
– Bohemian♦
May 29 '14 at 15:18
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". When input.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine()
immediately after input.nextInt()
It's because when you enter a number then press Enter, input.nextInt()
consumes only the number, not the "end of line". When input.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input.
Instead, use input.nextLine()
immediately after input.nextInt()
answered Aug 14 '11 at 12:25
Bohemian♦Bohemian
302k65432574
302k65432574
Mmm, that bug was corrected in now a days?
– Victor
May 29 '14 at 13:28
7
@Victor it's not bug. it's working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.
– Bohemian♦
May 29 '14 at 13:38
I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this "issue" in the next JCP.
– Victor
May 29 '14 at 14:55
@victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.
– Bohemian♦
May 29 '14 at 15:18
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
Mmm, that bug was corrected in now a days?
– Victor
May 29 '14 at 13:28
7
@Victor it's not bug. it's working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.
– Bohemian♦
May 29 '14 at 13:38
I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this "issue" in the next JCP.
– Victor
May 29 '14 at 14:55
@victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.
– Bohemian♦
May 29 '14 at 15:18
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
Mmm, that bug was corrected in now a days?
– Victor
May 29 '14 at 13:28
Mmm, that bug was corrected in now a days?
– Victor
May 29 '14 at 13:28
7
7
@Victor it's not bug. it's working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.
– Bohemian♦
May 29 '14 at 13:38
@Victor it's not bug. it's working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.
– Bohemian♦
May 29 '14 at 13:38
I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this "issue" in the next JCP.
– Victor
May 29 '14 at 14:55
I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this "issue" in the next JCP.
– Victor
May 29 '14 at 14:55
@victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.
– Bohemian♦
May 29 '14 at 15:18
@victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.
– Bohemian♦
May 29 '14 at 15:18
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
There seem to be many questions about this issue with java.util.Scanner
. I think a more readable/idiomatic solution would be to call scanner.skip("[rn]+")
to drop any newline characters after calling nextInt()
.
EDIT: as @PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
I know what we do to remove the data in buffer, but this case, please help me with this: stackoverflow.com/questions/33585314/having-issues-with-scanner
– Khuong
Nov 7 '15 at 18:03
FYI, this will cause an infinite loop is the user types any tabs or spaces after the numeric input. See my answer here for a better skip: stackoverflow.com/a/42471816/7098259
– Patrick Parker
Feb 26 '17 at 17:52
@PatrickParker: it does indeed cause an infinite loop! Thanks, edited the answer to link to yours.
– Denis Tulskiy
Feb 27 '17 at 5:57
@PatrickParker Why does is cause infinite loop ?
– Piyush
Aug 19 '17 at 8:41
add a comment |
There seem to be many questions about this issue with java.util.Scanner
. I think a more readable/idiomatic solution would be to call scanner.skip("[rn]+")
to drop any newline characters after calling nextInt()
.
EDIT: as @PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
I know what we do to remove the data in buffer, but this case, please help me with this: stackoverflow.com/questions/33585314/having-issues-with-scanner
– Khuong
Nov 7 '15 at 18:03
FYI, this will cause an infinite loop is the user types any tabs or spaces after the numeric input. See my answer here for a better skip: stackoverflow.com/a/42471816/7098259
– Patrick Parker
Feb 26 '17 at 17:52
@PatrickParker: it does indeed cause an infinite loop! Thanks, edited the answer to link to yours.
– Denis Tulskiy
Feb 27 '17 at 5:57
@PatrickParker Why does is cause infinite loop ?
– Piyush
Aug 19 '17 at 8:41
add a comment |
There seem to be many questions about this issue with java.util.Scanner
. I think a more readable/idiomatic solution would be to call scanner.skip("[rn]+")
to drop any newline characters after calling nextInt()
.
EDIT: as @PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585
There seem to be many questions about this issue with java.util.Scanner
. I think a more readable/idiomatic solution would be to call scanner.skip("[rn]+")
to drop any newline characters after calling nextInt()
.
EDIT: as @PatrickParker noted below, this will cause an infinite loop if user inputs any whitespace after the number. See their answer for a better pattern to use with skip: https://stackoverflow.com/a/42471816/143585
edited May 23 '17 at 12:10
Community♦
11
11
answered Mar 23 '14 at 16:35
Denis TulskiyDenis Tulskiy
16.5k54262
16.5k54262
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
I know what we do to remove the data in buffer, but this case, please help me with this: stackoverflow.com/questions/33585314/having-issues-with-scanner
– Khuong
Nov 7 '15 at 18:03
FYI, this will cause an infinite loop is the user types any tabs or spaces after the numeric input. See my answer here for a better skip: stackoverflow.com/a/42471816/7098259
– Patrick Parker
Feb 26 '17 at 17:52
@PatrickParker: it does indeed cause an infinite loop! Thanks, edited the answer to link to yours.
– Denis Tulskiy
Feb 27 '17 at 5:57
@PatrickParker Why does is cause infinite loop ?
– Piyush
Aug 19 '17 at 8:41
add a comment |
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
I know what we do to remove the data in buffer, but this case, please help me with this: stackoverflow.com/questions/33585314/having-issues-with-scanner
– Khuong
Nov 7 '15 at 18:03
FYI, this will cause an infinite loop is the user types any tabs or spaces after the numeric input. See my answer here for a better skip: stackoverflow.com/a/42471816/7098259
– Patrick Parker
Feb 26 '17 at 17:52
@PatrickParker: it does indeed cause an infinite loop! Thanks, edited the answer to link to yours.
– Denis Tulskiy
Feb 27 '17 at 5:57
@PatrickParker Why does is cause infinite loop ?
– Piyush
Aug 19 '17 at 8:41
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
I know what we do to remove the data in buffer, but this case, please help me with this: stackoverflow.com/questions/33585314/having-issues-with-scanner
– Khuong
Nov 7 '15 at 18:03
I know what we do to remove the data in buffer, but this case, please help me with this: stackoverflow.com/questions/33585314/having-issues-with-scanner
– Khuong
Nov 7 '15 at 18:03
FYI, this will cause an infinite loop is the user types any tabs or spaces after the numeric input. See my answer here for a better skip: stackoverflow.com/a/42471816/7098259
– Patrick Parker
Feb 26 '17 at 17:52
FYI, this will cause an infinite loop is the user types any tabs or spaces after the numeric input. See my answer here for a better skip: stackoverflow.com/a/42471816/7098259
– Patrick Parker
Feb 26 '17 at 17:52
@PatrickParker: it does indeed cause an infinite loop! Thanks, edited the answer to link to yours.
– Denis Tulskiy
Feb 27 '17 at 5:57
@PatrickParker: it does indeed cause an infinite loop! Thanks, edited the answer to link to yours.
– Denis Tulskiy
Feb 27 '17 at 5:57
@PatrickParker Why does is cause infinite loop ?
– Piyush
Aug 19 '17 at 8:41
@PatrickParker Why does is cause infinite loop ?
– Piyush
Aug 19 '17 at 8:41
add a comment |
It does that because input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding an input.nextLine();
underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
you have to use try catch here. What will happen if the input is not a number. NumberFormatException need to be handled here.
– Arundev
Mar 25 at 11:46
add a comment |
It does that because input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding an input.nextLine();
underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
you have to use try catch here. What will happen if the input is not a number. NumberFormatException need to be handled here.
– Arundev
Mar 25 at 11:46
add a comment |
It does that because input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding an input.nextLine();
underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
It does that because input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding an input.nextLine();
underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
answered Feb 23 '13 at 22:01
Electric CoffeeElectric Coffee
5,82224099
5,82224099
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
you have to use try catch here. What will happen if the input is not a number. NumberFormatException need to be handled here.
– Arundev
Mar 25 at 11:46
add a comment |
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
you have to use try catch here. What will happen if the input is not a number. NumberFormatException need to be handled here.
– Arundev
Mar 25 at 11:46
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
you have to use try catch here. What will happen if the input is not a number. NumberFormatException need to be handled here.
– Arundev
Mar 25 at 11:46
you have to use try catch here. What will happen if the input is not a number. NumberFormatException need to be handled here.
– Arundev
Mar 25 at 11:46
add a comment |
Things you need to know:
text which represents few lines also contains non-printable characters between lines (we call them line separators) like
- carriage return (CR - in String literals represented as
"r"
) - line feed (LF - in String literals represented as
"n"
)
- carriage return (CR - in String literals represented as
when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by
System.in
which is read byScanner
) also sends OS dependant line separators (like for Windowsrn
) after it.
So when you are asking the user for value like
age
, and user types 42 and presses enter, standard input will contain"42rn"
.
Problem
Scanner#nextInt
(and other Scanner#nextType
methods) doesn't allow Scanner to consume these line separators. It will read them from System.in
(how else Scanner would know that there are no more digits from the user which represent age
value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.
Now Scanner#nextLine()
simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine
also consumes those line separators.
Solution
So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine
, either
- consume line separator left by
nextInt
from Scanners cache by
- calling
nextLine
, - or by calling
skip("\R")
to let Scanner skip part matched byR
which represents line separator (more info aboutR
: https://stackoverflow.com/a/31060125)
- calling
- don't use
nextInt
(nornext
, or anynextTYPE
methods) at all. Instead read entire data line-by-line usingnextLine
and parse numbers from each line (assuming one line contains only one number) to proper type likeint
viaInteger.parseInt
.
BTW: Scanner#nextType
methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42rnrn321rnrnrnfoobar"
code
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
will be able to properly assign num1=42
num2=321
name=foobar
.
add a comment |
Things you need to know:
text which represents few lines also contains non-printable characters between lines (we call them line separators) like
- carriage return (CR - in String literals represented as
"r"
) - line feed (LF - in String literals represented as
"n"
)
- carriage return (CR - in String literals represented as
when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by
System.in
which is read byScanner
) also sends OS dependant line separators (like for Windowsrn
) after it.
So when you are asking the user for value like
age
, and user types 42 and presses enter, standard input will contain"42rn"
.
Problem
Scanner#nextInt
(and other Scanner#nextType
methods) doesn't allow Scanner to consume these line separators. It will read them from System.in
(how else Scanner would know that there are no more digits from the user which represent age
value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.
Now Scanner#nextLine()
simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine
also consumes those line separators.
Solution
So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine
, either
- consume line separator left by
nextInt
from Scanners cache by
- calling
nextLine
, - or by calling
skip("\R")
to let Scanner skip part matched byR
which represents line separator (more info aboutR
: https://stackoverflow.com/a/31060125)
- calling
- don't use
nextInt
(nornext
, or anynextTYPE
methods) at all. Instead read entire data line-by-line usingnextLine
and parse numbers from each line (assuming one line contains only one number) to proper type likeint
viaInteger.parseInt
.
BTW: Scanner#nextType
methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42rnrn321rnrnrnfoobar"
code
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
will be able to properly assign num1=42
num2=321
name=foobar
.
add a comment |
Things you need to know:
text which represents few lines also contains non-printable characters between lines (we call them line separators) like
- carriage return (CR - in String literals represented as
"r"
) - line feed (LF - in String literals represented as
"n"
)
- carriage return (CR - in String literals represented as
when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by
System.in
which is read byScanner
) also sends OS dependant line separators (like for Windowsrn
) after it.
So when you are asking the user for value like
age
, and user types 42 and presses enter, standard input will contain"42rn"
.
Problem
Scanner#nextInt
(and other Scanner#nextType
methods) doesn't allow Scanner to consume these line separators. It will read them from System.in
(how else Scanner would know that there are no more digits from the user which represent age
value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.
Now Scanner#nextLine()
simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine
also consumes those line separators.
Solution
So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine
, either
- consume line separator left by
nextInt
from Scanners cache by
- calling
nextLine
, - or by calling
skip("\R")
to let Scanner skip part matched byR
which represents line separator (more info aboutR
: https://stackoverflow.com/a/31060125)
- calling
- don't use
nextInt
(nornext
, or anynextTYPE
methods) at all. Instead read entire data line-by-line usingnextLine
and parse numbers from each line (assuming one line contains only one number) to proper type likeint
viaInteger.parseInt
.
BTW: Scanner#nextType
methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42rnrn321rnrnrnfoobar"
code
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
will be able to properly assign num1=42
num2=321
name=foobar
.
Things you need to know:
text which represents few lines also contains non-printable characters between lines (we call them line separators) like
- carriage return (CR - in String literals represented as
"r"
) - line feed (LF - in String literals represented as
"n"
)
- carriage return (CR - in String literals represented as
when you are reading data from the console, it allows the user to type his response and when he is done he needs to somehow confirm that fact. To do so, the user is required to press "enter"/"return" key on the keyboard.
What is important is that this key beside ensuring placing user data to standard input (represented by
System.in
which is read byScanner
) also sends OS dependant line separators (like for Windowsrn
) after it.
So when you are asking the user for value like
age
, and user types 42 and presses enter, standard input will contain"42rn"
.
Problem
Scanner#nextInt
(and other Scanner#nextType
methods) doesn't allow Scanner to consume these line separators. It will read them from System.in
(how else Scanner would know that there are no more digits from the user which represent age
value than facing whitespace?) which will remove them from standard input, but it will also cache those line separators internally. What we need to remember, is that all of the Scanner methods are always scanning starting from the cached text.
Now Scanner#nextLine()
simply collects and returns all characters until it finds line separators (or end of stream). But since line separators after reading the number from the console are found immediately in Scanner's cache, it returns empty String, meaning that Scanner was not able to find any character before those line separators (or end of stream).
BTW nextLine
also consumes those line separators.
Solution
So when you want to ask for number and then for entire line while avoiding that empty string as result of nextLine
, either
- consume line separator left by
nextInt
from Scanners cache by
- calling
nextLine
, - or by calling
skip("\R")
to let Scanner skip part matched byR
which represents line separator (more info aboutR
: https://stackoverflow.com/a/31060125)
- calling
- don't use
nextInt
(nornext
, or anynextTYPE
methods) at all. Instead read entire data line-by-line usingnextLine
and parse numbers from each line (assuming one line contains only one number) to proper type likeint
viaInteger.parseInt
.
BTW: Scanner#nextType
methods can skip delimiters (by default all whitespaces like tabs, line separators) including those cached by scanner, until they will find next non-delimiter value (token). Thanks to that for input like "42rnrn321rnrnrnfoobar"
code
int num1 = sc.nextInt();
int num2 = sc.nextInt();
String name = sc.next();
will be able to properly assign num1=42
num2=321
name=foobar
.
edited Aug 15 '18 at 16:29
answered Oct 9 '16 at 22:51
PshemoPshemo
96.4k15135194
96.4k15135194
add a comment |
add a comment |
Instead of input.nextLine()
use input.next()
, that should solve the problem.
Modified code:
public static Scanner input = new Scanner(System.in);
public static void main(String args)
{
System.out.print("Insert a number: ");
int number = input.nextInt();
System.out.print("Text1: ");
String text1 = input.next();
System.out.print("Text2: ");
String text2 = input.next();
}
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
Instead of input.nextLine()
use input.next()
, that should solve the problem.
Modified code:
public static Scanner input = new Scanner(System.in);
public static void main(String args)
{
System.out.print("Insert a number: ");
int number = input.nextInt();
System.out.print("Text1: ");
String text1 = input.next();
System.out.print("Text2: ");
String text2 = input.next();
}
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
Instead of input.nextLine()
use input.next()
, that should solve the problem.
Modified code:
public static Scanner input = new Scanner(System.in);
public static void main(String args)
{
System.out.print("Insert a number: ");
int number = input.nextInt();
System.out.print("Text1: ");
String text1 = input.next();
System.out.print("Text2: ");
String text2 = input.next();
}
Instead of input.nextLine()
use input.next()
, that should solve the problem.
Modified code:
public static Scanner input = new Scanner(System.in);
public static void main(String args)
{
System.out.print("Insert a number: ");
int number = input.nextInt();
System.out.print("Text1: ");
String text1 = input.next();
System.out.print("Text2: ");
String text2 = input.next();
}
edited Jul 23 '14 at 10:31
arghtype
3,243113348
3,243113348
answered Jul 23 '14 at 10:20
CastaldiCastaldi
384417
384417
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
FYI: merged from stackoverflow.com/questions/7056749/…
– Shog9♦
Nov 13 '14 at 19:12
add a comment |
In order to avoid the issue, use nextLine();
immediately after nextInt();
as it helps in clearing out the buffer. When you press ENTER
the nextInt();
does not capture the new line and hence, skips the Scanner
code later.
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer
add a comment |
In order to avoid the issue, use nextLine();
immediately after nextInt();
as it helps in clearing out the buffer. When you press ENTER
the nextInt();
does not capture the new line and hence, skips the Scanner
code later.
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer
add a comment |
In order to avoid the issue, use nextLine();
immediately after nextInt();
as it helps in clearing out the buffer. When you press ENTER
the nextInt();
does not capture the new line and hence, skips the Scanner
code later.
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer
In order to avoid the issue, use nextLine();
immediately after nextInt();
as it helps in clearing out the buffer. When you press ENTER
the nextInt();
does not capture the new line and hence, skips the Scanner
code later.
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer
answered Nov 17 '16 at 0:51
Urvashi GuptaUrvashi Gupta
257310
257310
add a comment |
add a comment |
If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .
Code :
class ScanReader {
/**
* @author Nikunj Khokhar
*/
private byte buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}
public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == 'n' || n == 'r' || n == 't' || n == -1) return true;
else return false;
}
public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public void scanLong(long A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}
public void scanInt(int A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}
}
Advantages :
- Scans Input faster than BufferReader
- Reduces Time Complexity
- Flushes Buffer for every next input
Methods :
- scanChar() - scan single character
- scanInt() - scan Integer value
- scanLong() - scan Long value
- scanString() - scan String value
- scanDouble() - scan Double value
- scanInt(int array) - scans complete Array(Integer)
- scanLong(long array) - scans complete Array(Long)
Usage :
- Copy the Given Code below your java code.
- Initialise Object for Given Class
ScanReader sc = new ScanReader(System.in);
3. Import necessary Classes :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4. Throw IOException from your main method to handle Exception
5. Use Provided Methods.
6. Enjoy
Example :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
ScanReader sc = new ScanReader(System.in);
int a=sc.scanInt();
System.out.println(a);
}
}
class ScanReader....
add a comment |
If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .
Code :
class ScanReader {
/**
* @author Nikunj Khokhar
*/
private byte buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}
public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == 'n' || n == 'r' || n == 't' || n == -1) return true;
else return false;
}
public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public void scanLong(long A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}
public void scanInt(int A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}
}
Advantages :
- Scans Input faster than BufferReader
- Reduces Time Complexity
- Flushes Buffer for every next input
Methods :
- scanChar() - scan single character
- scanInt() - scan Integer value
- scanLong() - scan Long value
- scanString() - scan String value
- scanDouble() - scan Double value
- scanInt(int array) - scans complete Array(Integer)
- scanLong(long array) - scans complete Array(Long)
Usage :
- Copy the Given Code below your java code.
- Initialise Object for Given Class
ScanReader sc = new ScanReader(System.in);
3. Import necessary Classes :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4. Throw IOException from your main method to handle Exception
5. Use Provided Methods.
6. Enjoy
Example :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
ScanReader sc = new ScanReader(System.in);
int a=sc.scanInt();
System.out.println(a);
}
}
class ScanReader....
add a comment |
If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .
Code :
class ScanReader {
/**
* @author Nikunj Khokhar
*/
private byte buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}
public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == 'n' || n == 'r' || n == 't' || n == -1) return true;
else return false;
}
public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public void scanLong(long A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}
public void scanInt(int A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}
}
Advantages :
- Scans Input faster than BufferReader
- Reduces Time Complexity
- Flushes Buffer for every next input
Methods :
- scanChar() - scan single character
- scanInt() - scan Integer value
- scanLong() - scan Long value
- scanString() - scan String value
- scanDouble() - scan Double value
- scanInt(int array) - scans complete Array(Integer)
- scanLong(long array) - scans complete Array(Long)
Usage :
- Copy the Given Code below your java code.
- Initialise Object for Given Class
ScanReader sc = new ScanReader(System.in);
3. Import necessary Classes :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4. Throw IOException from your main method to handle Exception
5. Use Provided Methods.
6. Enjoy
Example :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
ScanReader sc = new ScanReader(System.in);
int a=sc.scanInt();
System.out.println(a);
}
}
class ScanReader....
If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .
Code :
class ScanReader {
/**
* @author Nikunj Khokhar
*/
private byte buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}
public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == 'n' || n == 'r' || n == 't' || n == -1) return true;
else return false;
}
public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public void scanLong(long A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}
public void scanInt(int A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}
}
Advantages :
- Scans Input faster than BufferReader
- Reduces Time Complexity
- Flushes Buffer for every next input
Methods :
- scanChar() - scan single character
- scanInt() - scan Integer value
- scanLong() - scan Long value
- scanString() - scan String value
- scanDouble() - scan Double value
- scanInt(int array) - scans complete Array(Integer)
- scanLong(long array) - scans complete Array(Long)
Usage :
- Copy the Given Code below your java code.
- Initialise Object for Given Class
ScanReader sc = new ScanReader(System.in);
3. Import necessary Classes :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
4. Throw IOException from your main method to handle Exception
5. Use Provided Methods.
6. Enjoy
Example :
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
ScanReader sc = new ScanReader(System.in);
int a=sc.scanInt();
System.out.println(a);
}
}
class ScanReader....
answered Jun 16 '17 at 8:12
NIKUNJ KHOKHARNIKUNJ KHOKHAR
391314
391314
add a comment |
add a comment |
If you want to read both strings and ints, a solution is to use two Scanners:
Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);
intScanner.close();
stringScanner.close();
add a comment |
If you want to read both strings and ints, a solution is to use two Scanners:
Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);
intScanner.close();
stringScanner.close();
add a comment |
If you want to read both strings and ints, a solution is to use two Scanners:
Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);
intScanner.close();
stringScanner.close();
If you want to read both strings and ints, a solution is to use two Scanners:
Scanner stringScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
intScanner.nextInt();
String s = stringScanner.nextLine(); // unaffected by previous nextInt()
System.out.println(s);
intScanner.close();
stringScanner.close();
answered Jun 20 '17 at 18:52
André ValentiAndré Valenti
375310
375310
add a comment |
add a comment |
sc.nextLine()
is better as compared to parsing the input.
Because performance wise it will be good.
add a comment |
sc.nextLine()
is better as compared to parsing the input.
Because performance wise it will be good.
add a comment |
sc.nextLine()
is better as compared to parsing the input.
Because performance wise it will be good.
sc.nextLine()
is better as compared to parsing the input.
Because performance wise it will be good.
edited Sep 14 '17 at 10:45
Aurasphere
2,537103152
2,537103152
answered Sep 14 '17 at 10:16
shankar upadhyayshankar upadhyay
187210
187210
add a comment |
add a comment |
I guess I'm pretty late to the party..
As previously stated, calling input.nextLine()
after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1
. I'll just shed a little more light to the entire topic.
Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
If we input the value below (as a single line of input)
54 234
The value of our firstNumber
and secondNumber
variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().
nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".
Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.
I hope this helps.. Merry coding!
what is a "new line feed"?
– Abcd
Jan 13 at 16:22
@Abcd A new line feed basically means 'starting from a new line'.
– Taslim Oseni
Jan 13 at 19:35
add a comment |
I guess I'm pretty late to the party..
As previously stated, calling input.nextLine()
after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1
. I'll just shed a little more light to the entire topic.
Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
If we input the value below (as a single line of input)
54 234
The value of our firstNumber
and secondNumber
variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().
nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".
Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.
I hope this helps.. Merry coding!
what is a "new line feed"?
– Abcd
Jan 13 at 16:22
@Abcd A new line feed basically means 'starting from a new line'.
– Taslim Oseni
Jan 13 at 19:35
add a comment |
I guess I'm pretty late to the party..
As previously stated, calling input.nextLine()
after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1
. I'll just shed a little more light to the entire topic.
Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
If we input the value below (as a single line of input)
54 234
The value of our firstNumber
and secondNumber
variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().
nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".
Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.
I hope this helps.. Merry coding!
I guess I'm pretty late to the party..
As previously stated, calling input.nextLine()
after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1
. I'll just shed a little more light to the entire topic.
Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
If we input the value below (as a single line of input)
54 234
The value of our firstNumber
and secondNumber
variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().
nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".
Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.
I hope this helps.. Merry coding!
edited Jan 7 '18 at 10:40
answered Jan 7 '18 at 10:33
Taslim OseniTaslim Oseni
1,46341728
1,46341728
what is a "new line feed"?
– Abcd
Jan 13 at 16:22
@Abcd A new line feed basically means 'starting from a new line'.
– Taslim Oseni
Jan 13 at 19:35
add a comment |
what is a "new line feed"?
– Abcd
Jan 13 at 16:22
@Abcd A new line feed basically means 'starting from a new line'.
– Taslim Oseni
Jan 13 at 19:35
what is a "new line feed"?
– Abcd
Jan 13 at 16:22
what is a "new line feed"?
– Abcd
Jan 13 at 16:22
@Abcd A new line feed basically means 'starting from a new line'.
– Taslim Oseni
Jan 13 at 19:35
@Abcd A new line feed basically means 'starting from a new line'.
– Taslim Oseni
Jan 13 at 19:35
add a comment |
public static void main(String args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
– Neeraj Gahlawat
Jul 30 '17 at 3:50
add a comment |
public static void main(String args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
– Neeraj Gahlawat
Jul 30 '17 at 3:50
add a comment |
public static void main(String args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
public static void main(String args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
answered Jul 30 '17 at 3:48
Neeraj GahlawatNeeraj Gahlawat
51354
51354
If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
– Neeraj Gahlawat
Jul 30 '17 at 3:50
add a comment |
If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
– Neeraj Gahlawat
Jul 30 '17 at 3:50
If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
– Neeraj Gahlawat
Jul 30 '17 at 3:50
If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
– Neeraj Gahlawat
Jul 30 '17 at 3:50
add a comment |
Use 2 scanner objects instead of one
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
add a comment |
Use 2 scanner objects instead of one
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
add a comment |
Use 2 scanner objects instead of one
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
Use 2 scanner objects instead of one
Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
answered Jan 16 at 19:24
Harsh ShahHarsh Shah
292
292
add a comment |
add a comment |
Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.
int i = new Scanner(System.in).nextInt();
1
But then you have to close theScanner
to prevent memory leak. Wasting time?
– TheCoffeeCup
Oct 8 '15 at 1:22
Doesn't the GC take care of that if the Scanner is wrapped in a method? Like: String getInput() {return new Scanner(System.in).nextLine()};
– Tobias Johansson
Jun 1 '16 at 22:14
This is absolutely incorrect.nextInt()
won't consume the newline, regardless of whether it's in a "new"Scanner
or an already used one.
– Dawood ibn Kareem
Dec 29 '16 at 20:55
add a comment |
Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.
int i = new Scanner(System.in).nextInt();
1
But then you have to close theScanner
to prevent memory leak. Wasting time?
– TheCoffeeCup
Oct 8 '15 at 1:22
Doesn't the GC take care of that if the Scanner is wrapped in a method? Like: String getInput() {return new Scanner(System.in).nextLine()};
– Tobias Johansson
Jun 1 '16 at 22:14
This is absolutely incorrect.nextInt()
won't consume the newline, regardless of whether it's in a "new"Scanner
or an already used one.
– Dawood ibn Kareem
Dec 29 '16 at 20:55
add a comment |
Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.
int i = new Scanner(System.in).nextInt();
Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.
int i = new Scanner(System.in).nextInt();
answered Mar 13 '15 at 11:06
Tobias JohanssonTobias Johansson
180111
180111
1
But then you have to close theScanner
to prevent memory leak. Wasting time?
– TheCoffeeCup
Oct 8 '15 at 1:22
Doesn't the GC take care of that if the Scanner is wrapped in a method? Like: String getInput() {return new Scanner(System.in).nextLine()};
– Tobias Johansson
Jun 1 '16 at 22:14
This is absolutely incorrect.nextInt()
won't consume the newline, regardless of whether it's in a "new"Scanner
or an already used one.
– Dawood ibn Kareem
Dec 29 '16 at 20:55
add a comment |
1
But then you have to close theScanner
to prevent memory leak. Wasting time?
– TheCoffeeCup
Oct 8 '15 at 1:22
Doesn't the GC take care of that if the Scanner is wrapped in a method? Like: String getInput() {return new Scanner(System.in).nextLine()};
– Tobias Johansson
Jun 1 '16 at 22:14
This is absolutely incorrect.nextInt()
won't consume the newline, regardless of whether it's in a "new"Scanner
or an already used one.
– Dawood ibn Kareem
Dec 29 '16 at 20:55
1
1
But then you have to close the
Scanner
to prevent memory leak. Wasting time?– TheCoffeeCup
Oct 8 '15 at 1:22
But then you have to close the
Scanner
to prevent memory leak. Wasting time?– TheCoffeeCup
Oct 8 '15 at 1:22
Doesn't the GC take care of that if the Scanner is wrapped in a method? Like: String getInput() {return new Scanner(System.in).nextLine()};
– Tobias Johansson
Jun 1 '16 at 22:14
Doesn't the GC take care of that if the Scanner is wrapped in a method? Like: String getInput() {return new Scanner(System.in).nextLine()};
– Tobias Johansson
Jun 1 '16 at 22:14
This is absolutely incorrect.
nextInt()
won't consume the newline, regardless of whether it's in a "new" Scanner
or an already used one.– Dawood ibn Kareem
Dec 29 '16 at 20:55
This is absolutely incorrect.
nextInt()
won't consume the newline, regardless of whether it's in a "new" Scanner
or an already used one.– Dawood ibn Kareem
Dec 29 '16 at 20:55
add a comment |
protected by Aniket Thakur Apr 19 '15 at 9:05
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
4
Related: stackoverflow.com/questions/4708219/…
– James P.
Aug 14 '11 at 12:27
25
The newline character is probably not consumed.
– Lews Therin
Oct 27 '12 at 16:39
5
Style note: you should declare your String variables on the same line you assign a value. E.g.
String string1 = input.nextLine ()
.– Duncan Jones
Oct 27 '12 at 16:39
2
@Lews Therin: Yes, you are right. After another couple of test I found that it is executed and read "n". How to avoid of that?
– blekione
Oct 27 '12 at 16:45
3
Or you could be like me and use BufferedReader :) I don't care if it's old school, it has always worked and always will work for me. Also, knowledge of BufferedReader has application elsewhere. I simply don't like Scanner.
– Cruncher
Aug 27 '13 at 19:36