I am using a Scanner object to take user input. The Scanner first takes an integer called 'num'. I then create an array of Strings of size 'num' and I fill this array with Strings taken in by the same Scanner via a for-loop. My problem is that when taking the first String value, the Scanner seems to 'skip' it by assigning it an empty String. Why is it doing this?
import java.util.Scanner;
public class KrisKindle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many people are there?");
int num = scan.nextInt();
String[] names = new String[num];
for(int i = 0; i < names.length; i++) {
System.out.println("Enter name of person " + (i +1) + "/" + num);
names[i] = scan.nextLine();
}
}
}
Here's a sample output for when this program is run:
How many people are there?
7
Enter name of person 1/7
Enter name of person 2/7
Adam
Enter name of person 3/7
Eve
Enter name of person 4/7
What I have tried so far:
- Creating a separate Scanner object for taking my array of Strings. This causes a separate error that I can share if it might help
- Printing the value of name 1/7 (it is empty)