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

时间:2018-05-20 23:56:18

标签: java java.util.scanner

这是我的计划;重点是从用户获取一个边值并输出表面积和体积。我正在检查程序输入是否错误,比如输入一个字母而不是一个数字。当我只使用一个实例但在第二个和第三个实例上我收到错误时,它可以工作。我不确定我的问题在这里。

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)

1 个答案:

答案 0 :(得分:1)

您在这里关闭了System.in信息流:

sc.close();

阻止所有其他实例访问该流并从中读取,这就是您获取NoSuchElementException的原因。删除该行,你应该是好的。

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