gpt4 book ai didi

java.util.NoSuchElementException 错误?

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

我是一名初学者 Java 程序员,我正在尝试编写一个程序,允许用户通过输入名称、数量和质量来制作 Fruit 对象。我用构造函数创建了一个单独的水果类。当我要求用户输入名称时,一切都很好,但是当输入数量/质量时,我收到 java.util.NoSuchElementException 运行时错误。

这是我的代码

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();

}
}

最佳答案

您不需要创建多个扫描仪对象。当您关闭第一个扫描仪时,实际上您正在关闭System.in。所以第二个元素无法获取System.in。因此最好使用单一扫描仪进行所有输入检索

        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();

关于java.util.NoSuchElementException 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27747847/

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