1

I need get a String from prompt, and juste after I need get a String list from prompt. I have a problem. When I get my list, I have only the first word. I try any other nextLine() ... but do not work. I see lot of sample with juste 2 words (one space) but i looking for a list of word!!

Java code:

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

console result:

Enter a name:
aa
Enter a name list:
bb cc dd
Enter last name:
aa * bb ** cc

1st response is aa + enter

2nd response is bb cc dd + enter

but juste after dd + enter, the program display Enter last name: aa * bb ** cc and stop

Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154
  • 1
    Personally, I'd use `nextLine` for all the prompts and then a second `Scanner` to parse the "list" of values, but that's me - Remember, `next` will read the next token up to the next white space, so `nameList`, follows by `lastName` means that there are still tokens in the `Scanner` which `lastName` is picking up – MadProgrammer Mar 22 '18 at 20:43

1 Answers1

0

solution .nextLine() but on all lines

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a name:");
    String name = 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(name + " * " + nameList + " ** " + lastName);
}

Console:

Enter a name:
aa
Enter a name list:
bb cc dd
Enter last name:
ee
aa * bb cc dd ** ee
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154