Scanner Is Skipping Nextline() After Using Next() or Nextfoo()

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 each Scanner.nextInt or Scanner.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 using Integer.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



Leave a reply



Submit