1

I'm trying to make a GPA calculator but early on in the code I started having issues; here's the code segment:

    Scanner input = new Scanner(System.in);

    System.out.println("How many grades are you putting? ");
    int length = input.nextInt();

    String[] gradesArray = new String[length];

    for(int i = 0; i < gradesArray.length; i++)
    {
        System.out.println("Enter grade (include + or -) ");
        gradesArray[i] = input.nextLine();
    } 

it all goes well until the "Enter grade (include + or -) " part, it repeats twice, so when I compile and get to that part it says "Enter grade (include + or -) Enter grade (include + or -) " before I can type in anything. How can I fix this repeating issue? Because I think it also takes the spot of one grade.

Jesus
  • 33
  • 2

1 Answers1

2

You can fix this by adding

input.nextLine();

after

int length = input.nextInt();

This will make sure that the end of the line that contained that integer is consumed before you try to read more input.

Scanner input = new Scanner(System.in);

System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();

String[] gradesArray = new String[length];

for(int i = 0; i < gradesArray.length; i++)
{
    System.out.println("Enter grade (include + or -) ");
    gradesArray[i] = input.nextLine();
} 

Further explanation:

Calling input.nextInt() attempts to read a single token from the standard input and convert it to an int. After you type that integer and hit enter, the input stream still contains the end of line character[s], which haven't been read by input.nextInt(). Therefore, the first time you call input.nextLine(), it reads those characters and then discards them (since input.nextLine() strips newline characters), and you end up getting an empty String. That empty String is assigned to gradesArray[0], and the loop proceeds immediately to the next iteration. Adding an input.nextLine() before the loop solves the problem.

Eran
  • 359,724
  • 45
  • 626
  • 694
  • jesus christ, I love you right now. Would you mind explaining to me exactly why that works that way? :) – Jesus Dec 31 '14 at 07:08