简体   繁体   English

java.util.NoSuchElementException错误?

[英]java.util.NoSuchElementException Error?

I'm a beginner Java programmer, and I was trying to make a program that would allow the user to make a Fruit object by entering a name, quantity and mass. 我是一名Java初学者,我试图制作一个程序,允许用户通过输入名称,数量和质量来制作Fruit对象。 I made a seperate fruit class with a constructor. 我用构造函数制作了一个单独的水果类。 When I ask the user to input the name, everything is fine but when it gets to the quantity/mass I get a java.util.NoSuchElementException runtime error. 当我要求用户输入名称时,一切都很好,但是当达到数量/质量时,我会收到java.util.NoSuchElementException运行时错误。

This is my code 这是我的代码

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 + " and there's " + Quantity + " of it");
    }
}

import java.util.Scanner;

public class Fruits {

    public static void main (String[] args){

        Fruit Apple = new Fruit("Apple", 5, 32.6);
        System.out.println (Apple.Name);

            System.out.println("What would you like to name the fruit?: ");
            Scanner name1 = new Scanner (System.in);
            String name = name1.nextLine();
            name1.close();

            System.out.println("How much fruits are there?: ");
            Scanner quant1 = new Scanner (System.in);
            int quantity = quant1.nextInt();
            quant1.close();

            System.out.println("What is the mass of the Fruit?: ");
            Scanner mass1 = new Scanner (System.in);
            double mass = mass1.nextDouble();
            mass1.close();

            Fruit newFruit = new Fruit (name, quantity, mass);

            newFruit.Information();

    }
}

You don't need create multiple scanner objects. 您不需要创建多个扫描仪对象。 When you closing your first scanner actually you are closing System.in . 当您关闭第一台扫描仪时,实际上是在关闭System.in So second element can't get System.in. 因此,第二个元素无法获取System.in。 So it is better to use Single scanner for all input retrieval 因此最好使用Single扫描仪进行所有输入检索

        Scanner scanner = new Scanner (System.in);
        System.out.println("What would you like to name the fruit?: ");
        String name = scanner.nextLine();
        System.out.println("How much fruits are there?: ");
        int quantity = scanner.nextInt();
        System.out.println("What is the mass of the Fruit?: ");
        double mass = scanner.nextDouble();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM