gpt4 book ai didi

java - 循环键盘输入时出错

转载 作者:太空宇宙 更新时间:2023-11-04 06:52:54 25 4
gpt4 key购买 nike

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

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

最佳答案

keyboard.nextInt() 仅从键盘读取整数,而不读取返回字符。因此,当您第一次调用 keyboard.nextLine() 时,您将获得 getInt()\n

试试这个:

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

关于java - 循环键盘输入时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23120490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com