【问题标题】:Java Runtime Error for Calculating Area and Volume of Cylinder计算圆柱体面积和体积的 Java 运行时错误
【发布时间】:2018-02-19 22:20:37
【问题描述】:

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

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);
    }
}

我得到的错误是:

Exception in thread "main" java.util.NoSuchElementException at 
    java.util.Scanner.throwFor(Scanner.java:862) at 
    java.util.Scanner.next(Scanner.java:1485) at 
    java.util.Scanner.nextDouble(Scanner.java:2413) at
    Main.main(Main.java:10)

【问题讨论】:

  • 什么运行时错误?我没有看到。
  • 普罗霍罗夫先生您好。所以你的意思是这个程序会成功运行和终止,对吧?我目前正在使用我学校使用的评分程序,它说存在运行时错误......更具体地说: java.util.Scanner.throwFor(Scanner. java:862) 在 java.util.Scanner.next(Scanner.java:1485) 在 java.util.Scanner.nextDouble(Scanner.java:2413) 在 Main.main(Main.java:10) 这是什么意思?谢谢。
  • 我的意思是“你没有显示你的错误是什么。”现在你做了,但你应该从一开始就包含它。
  • 您只有一个键盘,因此,您只需要一个扫描仪,所以重复使用它。试试“长度 = input.nextInt();”并摆脱“新的 Scanner() 行
  • 老程序员怎么说。创建一个 Scanner once (您的程序的第一行已经在执行此操作)并删除所有其他 new Scanner 语句。

标签: java error-handling runtime-error


【解决方案1】:

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

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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多