2014-04-16 126 views
1

我有一个应该将信息存储到对象数组中的循环,但由于某种原因,它总是跳过第一个输入。键盘输入循环时出错

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++; 
    } 

回答

1

keyboard.nextInt()只读取键盘上的整数,而不是读取返回字符。所以,当你第一次打电话给keyboard.nextLine()时,你会得到getInt()\n

试试这个:

int n1 = keyboard.nextInt(); 
keyboard.nextLine(); 
+0

太感谢你了! – user3543032

+0

很高兴帮助!如果您发现它有帮助,请记住接受答案。 – slaadvak