1

I'm using a scanner to input Strings to an array. When I use next(); it works correctly, but I need it to read the whole line in some cases. When I use nextLine(); it skips the first element.

System.out.print("How many extras?: ");
        int extras = keybo.nextInt();
        String[] extraArray = new String[extras];
        for (int i = 1; i<=extras; i++)
        {
            System.out.println("Enter extra " + i + ": ");
            extraArray[i-1] = keybo.nextLine();
        }
        sandwich1.setExtras(extraArray);

This code outputs:

How many extras?: 3
Enter extra 1: Enter extra 2: bacon
Enter extra 3: lettuce

Extras: , bacon, lettuce

I actually just broke my code, but when I use this:

System.out.print("How many extras?: ");
        int extras = keybo.nextInt();
        String[] extraArray = new String[extras];
        for (int i = 1; i<=extras; i++)
        {
            System.out.println("Enter extra " + i + ": ");
            extraArray[i-1] = keybo.next();
        }

I get:

How many extras?: 3
Enter extra 1: 
bacon
Enter extra 2: 
extra cheese
Enter extra 3:

Extras: bacon, extra, cheese

Is there something I'm missing? Why does it loop through once without getting an input?

DrSooch
  • 322
  • 1
  • 8
  • I figured it out. The nextInt(); did not start a new line therefor, my first nextLine(); was skipped – DrSooch Mar 30 '18 at 05:05

0 Answers0