gpt4 book ai didi

Java 立方体程序在第二个和第三个实例上存在问题

转载 作者:行者123 更新时间:2023-11-30 06:10:05 26 4
gpt4 key购买 nike

这是我的程序;其要点是从用户处获取侧面值并输出表面积和体积。我正在检查程序中是否有错误的输入,例如输入字母而不是数字。当我只使用一个实例时它有效,但在第二个和第三个实例上我收到错误。我不确定我的问题在这里。

import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.*;

public class cube

{
private double side;

public double getLength(){

Scanner sc = new Scanner(System.in);

while(true){
try{
System.out.println("Please enter an integer: ");
side = sc.nextDouble();
break;

}
catch(InputMismatchException a){

System.err.println("\nWrong character");
sc.next();
continue;
}
}
sc.close();
return side;
}

/*
* Calculate the Surface Are of the cube base on the user side input
*/
public double calculateSurfaceArea(){

return 6 * side * side;
}

/*
* Calculate the volume of the cube base on the user side input
*/
public double calculateVolume(){

return side * side * side;
}


/**
* main() -- creates an instance of Cube and tests it
*/
public static void main(String args[]) throws IOException
{

// HINT: input the side from the keyboard and check for errors and exceptions
cube cube1 = new cube();

// Print the test results
System.out.println("\nSide length of cube1 is " + cube1.getLength());
System.out.println("Surface Area of cube1 is " + cube1.calculateSurfaceArea ());
System.out.println("Volume of cube1 is " + cube1.calculateVolume());
// Hint - add two more cube instances

cube cube2 = new cube();

// Print the test results
System.out.println("\nSide length of cube2 is " + cube2.getLength());
System.out.println("Surface Area of cube2 is " + cube2.calculateSurfaceArea ());
System.out.println("Volume of cube2 is " + cube2.calculateVolume());

cube cube3 = new cube();

// Print the test results
System.out.println("\nSide length of cube3 is " + cube3.getLength());
System.out.println("Surface Area of cube3 is " + cube3.calculateSurfaceArea ());
System.out.println("Volume of cube3 is " + cube3.calculateVolume());
} // main() } // Cube

错误是:

 Please enter an integer: 
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at folder.name.........(cube.java:18)
at folder.name.........(cube.java:68)

最佳答案

您将在此处关闭 System.in 流:

sc.close();

阻止所有其他实例访问该流并从中读取数据,这就是您收到 NoSuchElementException 的原因。删除该行,您应该就可以了。

作为一般规则,永远不要关闭系统流(输入、输出或错误)。应用程序的其他部分可能依赖于它们,如果它们关闭,您每次都会得到这个神秘的异常。

关于Java 立方体程序在第二个和第三个实例上存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440428/

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