0

take a look at the following code:

package com.company;

import java.util.Scanner;



public class Main {

    public static void main(String[] args) {
    // write your code here


            Scanner input = new Scanner (System.in);

            System.out.print("Enter the number of students: ");
            int numberOfStudents = input.nextInt();

            String[] students = new String [numberOfStudents];

            //input.nextLine();


            for (int i = 0; i < students.length; i++){
                System.out.println("Enter name for student " + (i+1) + ":"    );
                students[i] = input.nextLine();

            }

            for (int i = 0; i < students.length; i++){
                System.out.println(students[i]);

            }
        }

    }

You can see I commented out the statement "input.nextLine();" just before the first loop, and if I execute this code (this was my original code), the loop runs twice and then stops and waits for my input, then continues normally, so in order to fix this I need to put in that commented line and then it works normally, stops after every iteration and asks for input. Why is it like this, how exactly does Scanner work ?

Example output:

Without input.nextLine(); before the loop:

Enter the number of students: 4
Enter name for student 1:
Enter name for student 2:
name1 name2
Enter name for student 3:
name3
Enter name for student 4:
name4

And if I uncomment the input.nextLine(); the output is as follows:

Enter the number of students: 4
Enter name for student 1:
name1
Enter name for student 2:
name2
Enter name for student 3:
name3
Enter name for student 4:
name4

now it executes normally.

  • 1
    This is expected behavior. Using `nextInt()` does not terminate the line, so you must use `nextLine()` in between your next use of `nextLine()` in order to wait for more input. – Zircon Feb 16 '17 at 21:46
  • 1
    ** because the line //input.nextLine(); reads the user input string anf throws it away. It doesn't assign it to anything. it start storing in the for-loop – Seek Addo Feb 16 '17 at 21:46

1 Answers1

0

In the for loop, you need to replace input.nextLine(); with input.next(); as nextLine() method advances the scanner to next line and returns what was read whereas next() waits for next input. Below would work:

Scanner input = new Scanner(System.in);

System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();

String[] students = new String[numberOfStudents];

// input.nextLine();

for (int i = 0; i < students.length; i++) {
    System.out.println("Enter name for student " + (i + 1) + ":");
    students[i] = input.next();

}

for (int i = 0; i < students.length; i++) {
    System.out.println(students[i]);

}
Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81
  • Very nice, thank you, it's a new thing to have in mind for future problems. –  Feb 16 '17 at 22:23