计算圆柱体面积和体积的Java运行时误差

时间:2017-09-11 15:52:18

标签: java error-handling runtime-error

我有一个问题。该程序应该接收两个整数R和L(均在1和1000之间)并计算圆柱体的面积和体积。我的问题是我不断收到运行时错误。这是我的代码:

ContractState

我得到的错误是:

import java.util.Scanner;
public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int radius = input.nextInt();
        Scanner input2 = new Scanner(System.in);
        int length = input2.nextInt();

        while ((radius > 1000) || (radius < 1))
        {
            input = new Scanner(System.in);
            radius = input.nextInt();
        }

        while ((length > 1000) || (length < 1))
        {
            input2 = new Scanner(System.in);
            length = input2.nextInt();
        }

        double area = (radius * radius) * 3.14159;
        double volume = area * length;

        System.out.printf("%.1f\n", area);
        System.out.printf("%.1f\n", volume);
    }
}

1 个答案:

答案 0 :(得分:1)

在输入上调用netInt()之前,您需要检查它是否有一些输入。此外,您不需要每次都重新初始化输入和输入2。实际上你应该只使用一个输入扫描器

import java.util.Scanner;
public class Main
{

 public static void main(String[] args)
 {
    Scanner input = new Scanner(System.in);
    int radius = 0;
    if(input.hasNextInt() ){
        radius = input.nextInt();
    }
    int length = 0;
    //Scanner input2 = new Scanner(System.in);
    if(input.hasNextInt() ){
        length = input.nextInt();
    }
    while ((radius > 1000) || (radius < 1))
    {
       // input = new Scanner(System.in);
        if(input.hasNextInt() ){
          radius = input.nextInt();
        }
    }

    while ((length > 1000) || (length < 1))
    {
        //input2 = new Scanner(System.in);
        if(input.hasNextInt() ){
           length = input.nextInt();
        }
    }

    double area = (radius * radius) * 3.14159;
    double volume = area * length;

    System.out.printf("%.1f\n", area);
    System.out.printf("%.1f\n", volume);
  }
}