While using next() or nextfoo() , the upcoming nextLine() is skipped by scanner

0 votes
I am using "nextInt()" and "nextLine()" for reading input. The problem comes that after entering numerical value first "input.nextLine()" is skipped. Help me to  implement this.
Jun 6, 2018 in Java by sridhar
• 160 points
919 views

1 answer to this question.

0 votes

That's because the Scanner.nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine.

You will encounter the similar behaviour when you use "Scanner.nextLine" after Scanner.next() or any "Scanner.nextFoo" method.

you read the input through Scanner.nextLine and convert your input to the proper format you need. For examples, to an integer using "Integer.parseInt(String)" method.
int option = 0;
try {
    option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
String str1 = input.nextLine();

answered Jun 6, 2018 by mitto
• 160 points

Related Questions In Java

0 votes
1 answer

Why is the Scanner skipping nextLine() after using next() or nextFoo()

public static void main(String[] args) { ...READ MORE

answered Aug 27, 2018 in Java by samarth295
• 2,200 points
551 views
0 votes
2 answers

Scanner is skipping nextLine() after using next() or nextFoo()?

use input.nextLine(); after your nextInt() function for example:- input.nextInt(); ...READ MORE

answered May 11, 2019 in Java by Sourav Dangi
6,732 views
0 votes
1 answer

Is Java “pass-by-reference” or “pass-by-value”?

Think of reference parameters as being aliases ...READ MORE

answered Jun 8, 2018 in Java by Rishabh
• 3,580 points
337 views
0 votes
1 answer

Check whether the string is palindrome or not?

You may refer the below code: public static ...READ MORE

answered Jul 11, 2018 in Java by Akrati
• 3,170 points
221 views
0 votes
1 answer

How to find even or odd using call by value?

Call by value is, when a primitive ...READ MORE

answered Nov 23, 2018 in Java by Namitha
214 views
0 votes
1 answer

Is there a way to mask the password from java user input that comes from Scanner class and System.out.Println()?

You can use the console class to do so. ...READ MORE

answered May 27, 2019 in Java by Omkar
• 69,030 points
4,921 views
+1 vote
3 answers

What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,200 points
1,900 views
0 votes
2 answers

What is the syntax to initialize an array?

Rather than learning un-Official websites learn from ...READ MORE

answered Aug 2, 2018 in Java by samarth295
• 2,200 points
155 views
0 votes
2 answers

How do I get the current date and time using Java?

If you require a time stamp in ...READ MORE

answered Aug 23, 2019 in Java by Sirajul
• 58,210 points
350 views