2017-09-11 49 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? –