键盘输入循环时出错

时间:2014-04-16 21:28:38

标签: java arrays loops object 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++;
    }

1 个答案:

答案 0 :(得分:1)

keyboard.nextInt()只是从键盘读取一个整数,而不是读取返回字符。因此,当您第一次致电keyboard.nextLine()时,您会获得\n的{​​{1}}。

请改为尝试:

getInt()