当我的程序到达询问水果名称的部分时,它将输出询问名称的字符串,然后立即转到下一个字符串输出,而不等待用户输入。 这似乎会自动将 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/