2017-03-11 13 views
0

私は新しいjavaコーダーで、printfを使用して値を十二桁に丸めたときにエラーが発生しています。なぜ誰かが私に、そしてエラーを解決する方法を理解するのを助けることができますか?java.util.IllegalFormatPrecisionException printfを使用して小数点以下2桁に丸めたとき

コード

import java.util.Scanner; 

public class Demo 
{ 

    public static void main(String[] args) 
    { 

     int age = 0; 
     int count = 0; 
     int round = 0; 


     while ((age < 12) || (age > 18)) 
     { 

      Scanner input = new Scanner(System.in); 
      System.out.print("Enter a non-teen age: "); 
      age = input.nextInt();   

      if ((age < 12) || (age > 18)) 
      { 
       count = count + 1; 
       round = round + age; 
      } 
     } 

     System.out.println("Opps! " + age + " is a teen's age."); 
     System.out.println("Number of non-teens entered: " + count); 
     System.out.printf("Average of non-teens ages entered: %.2d",  round); 
    } 


} 

エラー:彼らは小数部を持っていないので、

Exception in thread "main" java.util.IllegalFormatPrecisionException: 2 
at java.util.Formatter$FormatSpecifier.checkInteger(Unknown Source) 
at java.util.Formatter$FormatSpecifier.<init>(Unknown Source) 
at java.util.Formatter.parse(Unknown Source) 
at java.util.Formatter.format(Unknown Source) 
at java.io.PrintStream.format(Unknown Source) 
at java.io.PrintStream.printf(Unknown Source) 
Demo.main(Demo.java:31) 
+2

これはJavaScriptではありません。 JavaとJavaScriptは完全に異なる言語であるため、タグを編集してください。 –

答えて

0

整数は小数点以下の桁を持つことができません。

"Average of non-teens ages entered: %.2f" 

はまた、あなたのround変数が現在の和を記憶している、あなたは平均年齢取得するcountことによってそれを分割する必要がありますので、::代わりにフロートを使用してみてください

System.out.printf("Average of non-teens ages entered: %.2f", (float)round/count); 
+0

ありがとうございました! –

1

を私はエラーがあると思いますこの行の

System.out.printf("Average of non-teens ages entered: %.2d",  round); 

「.2」は10進整数には意味がありません。それを削除する:

System.out.printf("Average of non-teens ages entered: %d",  round); 
+0

ありがとうございました! –

0

フォーマット指定子がprintfメソッドで使用される入力引数と一致しないためです。

int/double値の書式指定文字として、%dではなく%fを使用します。

+0

ありがとうございました! –

関連する問題