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.