Reputation: 21
I have a loop that is supposed to store information into an array of objects, but for some reason, it always skips the first input.
public class GerbilData {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("How many different food items do the gerbils eat?");
int n1 = keyboard.nextInt();
Food[] gerbilFood = new Food[n1];
String temp;
int temp2;
int count = 1;
for (int a = 0; a < n1; a++){
gerbilFood[a] = new Food();
}
int j = 0;
while (j < n1){
System.out.println("Name of food item " + count + ":");
temp = keyboard.nextLine();
gerbilFood[j].setName(temp);
count++;
j++;
}
Upvotes: 1
Views: 61
Reputation: 4779
keyboard.nextInt()
is only reading an integer from the keyboard, not reading the return character. So, when you first call keyboard.nextLine()
you get the \n
of the getInt()
.
Try this instead :
int n1 = keyboard.nextInt();
keyboard.nextLine();
Upvotes: 1