0

I'm working on a method that creates an ArrayList with strings (names) and the user is asked how many names will be inputted (size). Then, the program asks the user to type in a name, but when I run my program, it ignores the first entry, and just prints "Please enter a name" twice and when it outputs the ArrayList, the first element is a space. For example, it would ask: "How many names would you like to enter?" Let's say I type in 3. Then it says "Please enter a name," skips a line, and says "Please enter a name" again. (the main issue!) Let's say I type in Joe and then it prompts me again and I type in Poe. It outputs: [ , Joe, Poe]. Why does it ignore the first slot? Please note I'm a beginner...

 public static ArrayList<String> makeArrayList()
 {
   ArrayList<String> names = new ArrayList<String>(); 
   System.out.println("How many names would you like to enter?");
   int size = reader.nextInt();
   int count = 0;

   while (count < size)
   {
     System.out.println("Please enter a name.");  // asks for input
     String reply = reader.nextLine();
     names.add(reply);  // puts input into the ArrayList names
     count++;
    }

     return names;  // returns ArrayList names

 }
Janie
  • 41
  • 1
  • 9
  • It is never recommended to mix nextLine() with next() or nextInt(). Much better to simply use next() or nextInt() solely. so simply just use next() for the name and nextInt() for the size. Hope this helps. – gmanrocks Mar 13 '19 at 20:48
  • If you **need** to call `nextLine()` immediately after `nextXXX()`, use an extra to swallow the newline character. – FailingCoder Mar 13 '19 at 21:02
  • See this solution please: https://stackoverflow.com/questions/14452613/issues-with-nextline –  Mar 13 '19 at 22:49

0 Answers0