Reputation: 31
I'm a new java coder and am getting an error when using printf
to round a value to twodecimal places. Can anyone help me understand why, and how to resolve the error?
Code
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);
}
}
Error:
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)
Upvotes: 3
Views: 8050
Reputation: 2415
Because your format specifiers don't match input arguments used in the printf method.
Use %f rather than %d as the format specifier character for int/double values.
Upvotes: 0
Reputation: 19381
I guess the error is in this line
System.out.printf("Average of non-teens ages entered: %.2d", round);
'.2' does not make sense for decimal integers. Remove it:
System.out.printf("Average of non-teens ages entered: %d", round);
Upvotes: 3
Reputation: 566
Integers can’t have decimal places since they don’t have a fractional part. Try using a float instead:
"Average of non-teens ages entered: %.2f"
Also, your round
variable is currently storing a sum, so you need to divide it by count
to get the average age:
System.out.printf("Average of non-teens ages entered: %.2f", (float)round / count);
Upvotes: 0