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();
when I use nextInt() it skip on the next line
Please add input.nextLine() after reading the age i.e integer value.
for details refer this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Dogs my_dog = new Dogs();
System.out.println("What is the dog's name? ");
my_dog.setName(input.next());
System.out.println("What is the dog's age? ");
my_dog.setAge(input.nextInt());
// add this line
input.nextLine()
System.out.println("What is the dog's color? ");
my_dog.setColor(input.nextLine());
System.out.println("What is the owner's name? ");
my_dog.setOwner(input.nextLine());
}
}
Issues with nextLine();
The problem occurs as you hit the enter key, which is a newline \n
character. nextInt()
consumes only the integer, but it skips the newline \n
. To get around this problem, you may need to add an additional input.nextLine()
after you read the int
, which can consume the \n
.
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();.
// rest of the code
Related Topics
How to Convert a String to an Int in Java
How to Deal With "Java.Lang.Outofmemoryerror: Java Heap Space" Error
Converting Json Data to Java Object
Java: Maintaining Aspect Ratio of Jpanel Background Image
How to Set Environment Variables from Java
Why Is Using a Wild Card With a Java Import Statement Bad
How to Read All Files in a Folder from Java
Java String Split Removed Empty Values
Why Doesn't "System.Out.Println" Work in Android
Java Generics Type Erasure: When and What Happens
Including All the Jars in a Directory Within the Java Classpath
Variable Might Not Have Been Initialized Error
How to Pad an Integer With Zeros on the Left
Java Logical Operator Short-Circuiting
Inconsistent Performance Applying Foregroundactions in a Jeditorpane When Reading Html
How to Handle Infinite Loop Caused by Invalid Input (Inputmismatchexception) Using Scanner