【问题标题】:Error when looping on keyboard input循环键盘输入时出错
【发布时间】:2014-04-16 21:28:37
【问题描述】:

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

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

【问题讨论】:

    标签: java arrays loops object input


    【解决方案1】:

    keyboard.nextInt() 只是从键盘读取一个整数,而不是读取返回字符。因此,当您第一次调用 keyboard.nextLine() 时,您会得到 \ngetInt()

    试试这个:

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

    【讨论】:

    • 很高兴为您提供帮助!如果您觉得有帮助,请记得采纳答案。
    猜你喜欢
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多