gpt4 book ai didi

java - 程序跳过输入之一

转载 作者:行者123 更新时间:2023-12-01 18:20:35 24 4
gpt4 key购买 nike

当我的程序到达询问水果名称的部分时,它将输出询问名称的字符串,然后立即转到下一个字符串输出,而不等待用户输入。这似乎会自动将 null 值分配给我的 name 变量。

水果.java

public class Fruit {

String Name;
int Quantity;
double Mass;

public Fruit(String Name, int Quantity, double Mass) {
this.Name = Name;
this.Quantity = Quantity;
this.Mass = Mass;
}

public void Information() {
System.out.println("This fruit is an " + Name + ", there's " + Quantity
+ " of it and it weighs " + Mass + " grams");
}
}

水果.java

import java.util.Scanner;

public class Fruits {

public static void main(String[] args) {

Fruit menu[];
int number;
String name;
int quantity;
double mass;

System.out
.print("How many fruits would you like to add to the menu?: ");

Scanner input = new Scanner(System.in);

number = input.nextInt();
input.nextLine();
menu = new Fruit[number];

for (int i = 0; i < menu.length; i++) {

System.out.println("What would you like to name the fruit?: ");
name = input.nextLine();

System.out.println("How much fruits are there?: ");
quantity = input.nextInt();

System.out.println("What is the mass of the Fruit in grams?: ");
mass = input.nextDouble();

menu[i] = new Fruit(name, quantity, mass);

menu[i].Information();
}
input.close();
}
}

最佳答案

而不是 input.nextInt();使用Integer.parseInt(input.nextLine()) 。它可能会解决您的问题。

关于java - 程序跳过输入之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27768905/

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