2017-09-11 47 views
0

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

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) 
+3

什么运行时错误?我没有看到任何。 –

+0

你好普罗霍罗夫先生。 所以你的意思是这个程序会运行并终止成功,对吧? 我正在使用我的学校使用的评分程序,它说有一个运行时错误...更具体地说: 线程“main”中的异常java.util.NoSuchElementException \t at java.util.Scanner .throwFor(Scanner.java:862) \t在java.util.Scanner.next(Scanner.java:1485) \t在java.util.Scanner.nextDouble(Scanner.java:2413) \t在Main.main( Main.java:10) 这是什么意思?谢谢。 – Sean

+3

我的意思是“你不显示你的错误。”现在你做了,但你应该从一开始就包括它。 –

回答

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

为您工作@Sean? –