java.util.NoSuchElementException错误?
我是一个Java程序员初学者,我试图制作一个程序,允许用户通过输入名称、数量和质量来制作水果对象。我用构造函数创建了一个单独的水果类。当我要求用户输入名称时,一切正常,但当它达到数量/质量时,我会得到一个java.util.NoSuchElementException运行时错误 这是我的密码java.util.NoSuchElementException错误?,java,eclipse,java.util.scanner,Java,Eclipse,Java.util.scanner,我是一个Java程序员初学者,我试图制作一个程序,允许用户通过输入名称、数量和质量来制作水果对象。我用构造函数创建了一个单独的水果类。当我要求用户输入名称时,一切正常,但当它达到数量/质量时,我会得到一个java.util.NoSuchElementException运行时错误 这是我的密码 public class Fruit { String Name; int Quantity; double Mass; public Fruit (String Nam
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();
关闭扫描仪时,也会关闭底层System.in stream。只使用一个Scanner实例,完成后关闭它以提供所有输入。此外,为了遵循Java编码标准,变量应该是小写的。名称应该是名称,数量应该是数量,等等。。。