编译我的java代码时遇到错误。错误是:
Enter the length in centimeters: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Package.main(Package.java:11)
来自http://jsfiddle.net/tzxzawxp/的代码;
import java.util.Scanner;
public class Package
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
double length;
double width;
double height;
System.out.print("Enter the length in centimeters: ");
length = reader.nextDouble();
System.out.print("Enter the width in centimeters: ");
width = reader.nextDouble();
System.out.print("Enter the height in centimeters: ");
height = reader.nextDouble();
if (length <=0 | width <=0 | height <=0)
System.out.println("Invalid");
else
{
if (length < 10 && width < 10 && height < 10)
{
System.out.println ("Accept");
System.out.println("Volume is " + (length * width * height) + "cm");
System.out.println("Length is " + length);
System.out.println("Width is " + width);
System.out.println("Height is " + height);
if (length > 10 | width > 10 | height > 10)
System.out.println ("Reject");
}
}
}
}
任何人都知道如何解决此错误?
答案 0 :(得分:0)
它在第11行抛出NoSuchElementException
- &gt; length = reader.nextDouble();
它非常简单,无法从标准输入中读取新的双精度数。你确定你通过stdin传递这些参数吗?
注意:这是一个例外问题,代码确实可以正确编译
根据文件:http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextDouble()
抛出NoSuchElementException - 如果输入已用尽
答案 1 :(得分:0)
您的代码存在一些问题,因为一个Reject
永远不会输出逻辑嵌套的方式。
让我们从阅读输入开始(注意:不要关闭Scanner
缠绕System.in
- 它是全局的,
double[] values = new double[3];
String[] fields = { "length", "width", "height" };
int pos = 0;
while (pos < values.length) {
String field = fields[pos];
System.out.printf("Enter the %s in centimeters: ", field);
System.out.flush();
if (!reader.hasNext()) {
System.err.println("Nothing available from reader.");
System.exit(1);
}
if (reader.hasNextDouble()) {
values[pos++] = reader.nextDouble();
} else {
System.err.printf("%s is not a double.%n", reader.next());
}
}
另外请使用大括号,布尔或||
(不是|
)。等等,
double length = values[0];
double width = values[1];
double height = values[2];
// if (length <= 0 | width <= 0 | height <= 0)
if (length <= 0 || width <= 0 || height <= 0) {
System.out.println("Invalid");
} else {
if (length < 10 && width < 10 && height < 10) {
System.out.println("Accept");
System.out.println("Volume is " + (length * width * height)
+ "cm");
System.out.println("Length is " + length);
System.out.println("Width is " + width);
System.out.println("Height is " + height);
} else { // if (length > 10 | width > 10 | height > 10)
System.out.println("Reject");
}
}
答案 2 :(得分:0)
我在eclipse中执行了你的代码,运行程序时没有抛出任何异常。 请尝试一次eclipse,这是最好的学习方法。
希望你能毫无例外地运行。
我的输出:
以厘米为单位输入长度:0.3 以厘米为单位输入宽度:0.4 输入以厘米为单位的高度:0.5 接受 体积为0.06厘米 长度是0.3 宽度为0.4 高度为0.5