java - 程序跳过输入之一

标签 java arrays eclipse

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

相关文章:

java - 将两个 byteBuffer 连接成一个

JavaFx 在 Raspberry Pi 上非常慢

java - 无法在 Eclipse 中解析 import com.sun.javadoc

regex - 如何在 Eclipse 中替换/删除以特定单词开头的行?

java - Java 中的进程生成器

javascript - n%7 是什么意思?

java - 在 LocalDateTime 数组中存储日期和时间数组

Javascript函数可以使用reduce/map来计算对象属性的嵌套数组

c++ - 如何使用 new 在 C++ 中创建数组并初始化每个元素?

Java 程序从 Excel 文件读取数据抛出错误..需要帮助解决