0

I need get a number from prompt, and juste after I need get a String list from prompt. I have a problem. Is it OK if the 1st question ask a string with nextLine() see this post.

Java code:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number:");
    int num = input.nextInt();
    System.out.println("Enter a name list:");
    String nameList = input.nextLine();
    System.out.println("Enter last name:");
    String lastName = input.nextLine();
    input.close();
    System.out.println(num + " * " + nameList + " ** " + lastName);
}

console result:

Enter a number:
2
Enter a name list:
Enter last name:

1st response is 2 + enter

but juste after 2 + enter, the program display Enter a name list: Enter last name:

Stéphane GRILLON
  • 8,567
  • 5
  • 60
  • 106

2 Answers2

1

I would use input.next() instead of input.nextLine() as next blocks for user input while nextLine moves the scanner past the current line and it buffers all the inputs until it finds a line separator.

or use nextLine() after nextInt to consume the linefeed which is left by nextInt

humblefoolish
  • 389
  • 3
  • 14
0

Solution add input.nextLine(); juste after int num = input.nextInt();.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number:");
    int num = input.nextInt();
    input.nextLine();
    System.out.println("Enter a name list:");
    String nameList = input.nextLine();
    System.out.println("Enter last name:");
    String lastName = input.nextLine();
    input.close();
    System.out.println(num + " * " + nameList + " ** " + lastName);
}

console:

Enter a number:
2
Enter a name list:
aa bb cc
Enter last name:
dd
2 * aa bb cc ** dd
Stéphane GRILLON
  • 8,567
  • 5
  • 60
  • 106