0

In this code for a class assignment:

import java.util.Scanner;
public class StudentRoster
{
    public static void main (String [] args)
    {
        int names;
        Scanner input = new Scanner(System.in);
        System.out.println("How many students are in the class?");
        names = input.nextInt();
        String [] roster = new String [names];
        for (int i = 0; i < names; i++)
        {
            System.out.println("Enter student " + (i + 1) + "'s name: ");
            roster[i] = input.nextLine();
        }
        System.out.println("Student Roster");
        for (int i = 0; i < names; i++)
        {
            System.out.println(roster[i]);
        }
    }
}

Using the nextLine() method causes the first student's name to be skipped, if the next() method is used instead, the first student is skipped but spaces cannot be used? Why is this and how can I avoid it in the future?

  • 3
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – OH GOD SPIDERS Feb 04 '21 at 17:16

0 Answers0