Using scanner.nextLine()
I think your problem is that
int selection = scanner.nextInt();
reads just the number, not the end of line or anything after the number. When you declare
String sentence = scanner.nextLine();
This reads the remainder of the line with the number on it (with nothing after the number I suspect)
Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.
What's the difference between next() and nextLine() methods from Scanner class?
I always prefer to read input using nextLine()
and then parse the string.
Using next()
will only return what comes before the delimiter (defaults to whitespace). nextLine()
automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine()
would be str.split("\\s+")
.
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Why scan.next() + scan.nextLine() instead of scan.nextLine()
Reg. Scanner javadoc
next()
- Finds and returns the next complete token from this scanner.
nextLine()
- Advances this scanner past the current line and returns the input that was skipped.
So, with next()
basically it reads only first word, only 1st token (string) is being taken (remaining things are stored in the buffer, but nextLine()
allows you to read until enter is pressed= whole line.
Difference can be seen if you will try following snippet and try to put combinations of words and sentences:
Scanner sc = new Scanner(System.in);
System.out.println("first input:");
String tmp = sc.next();
System.out.println("tmp: '" + tmp +"'");
System.out.println("second input:");
tmp = sc.next() + sc.nextLine();
System.out.println("2nd tmp: '" + tmp +"'");
}
Inputs and outputs:
first input:
firstWord
tmp: 'firstWord'
second input:
second sentence
2nd tmp: 'second sentence'
//-------------
first input:
first sentencemorewords
tmp: 'first'
second input:
2nd tmp: 'sentencemorewords'
Maybe better explanation comes with direct printing:
Scanner sc = new Scanner(System.in);
System.out.println("first input:");
String tmp = sc.next();
System.out.println("tmp: '" + tmp +"'");
System.out.println("second input:");
System.out.println("next: " + sc.next() +",... nextLine: " + sc.nextLine());
Notice, only first word is handled by first
sc.next()
, in case of more words any other word will be handled by secondsc.next()
, but in case of more than 2 words, remaining string will be handled bynextLine
first input:
first second third more words
tmp: 'first'
second input:
next: second,... nextLine: third more words
So in your program if you need only one word, use
sc.next()
, if you need to read the whole line, usenextLine()
Scanner is skipping nextLine() after using next() or nextFoo()?
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 newlineint 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();
Scanner nextLine() issues
I think you're overcompensating with too many nextLine
s. You may want to do that once to clear the line after the int is inputted, for example, to clear the newline, but the second time here just absorbs an extra line of input:
System.out.println("You have not entered a valid number. Please enter a real number this time.");
in.nextLine();//first time
}
}
in.nextLine();//this second time is unnecessary.
The same thing happens with your duplicate uses here:
in.nextLine();
firstLetter = in.nextLine();
break;
You should only add an extra in.nextLine()
immediately between inputting nextSOMETHINGELSE()
and another nextLine()
.
EDIT:
Additionally, note that whenever you call in.nextLine()
, you are absorbing a line of input. For example, this line should be fixed:
if(in.nextLine().length() > 1){
because it reads in a line, using it up, and then checks whether that (now used-up) line is long enough.
Can't use Scanner.nextInt() and Scanner.nextLine() together
The problem is the '\n'
character that follows your integer. When you call nextInt
, the scanner reads the int
, but it does not consume the '\n'
character after it; nextLine
does that. That is why you get an empty line instead of the string that you were expecting to get.
Let's say your input has the following data:
12345
hello
Here is how the input buffer looks initially (^
represents the position at which the Scanner
reads the next piece of data):
1 2 3 4 5 \n h e l l o \n
^
After nextInt
, the buffer looks like this:
1 2 3 4 5 \n h e l l o \n
^
The first nextLine
consumes the \n
, leaving your buffer like this:
1 2 3 4 5 \n h e l l o \n
^
Now the nextLine
call will produce the expected result. Therefore, to fix your program, all you need is to add another call to nextLine
after nextInt
, and discard its result:
k = in.nextInt();
in.nextLine(); // Discard '\n'
input = in.nextLine();
Java How to get scanner.nextLine() on the same line?
Try:
System.out.print("--Television Show or Film (t or f): ");
String type = input.next();
Related Topics
Java: Prefix/Postfix of Increment/Decrement Operators
How to Prevent Java.Lang.Numberformatexception: For Input String: "N/A"
Why Do This() and Super() Have to Be the First Statement in a Constructor
What's the Difference Between Instant and Localdatetime
Java 8 Lambda Function That Throws Exception
Difference Between Applicationcontext.Xml and Spring-Servlet.Xml in Spring Framework
Fastest Way to Determine If an Integer'S Square Root Is an Integer
Which @Notnull Java Annotation Should I Use
Check Whether a String Is Not Null and Not Empty
How to Tell Gradle to Use Specific Jdk Version
How to Open a New Tab Using Selenium Webdriver in Java
How to Make Pipes Work With Runtime.Exec()
Difference Between ≪Context:Annotation-Config≫ and ≪Context:Component-Scan≫
Can an Abstract Class Have a Constructor
Why Filter() After Flatmap() Is "Not Completely" Lazy in Java Streams