Reputation: 377
I'm very new to Java and I'm just trying to get through some class exercises.
I've been given the task of calculating a user's perimeter and area of their circle from a given radius.
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
System.out.println("Please enter the radius of your circle below: ");
Scanner input = new Scanner(System.in);
float r =input.nextFloat();
float p = (float) (2 * Math.PI * r);
float a = (float) ((Math.PI) * Math.pow(r,2));
System.out.format("Your perimeter is %.3f", p + " and your area is %.3f", a);
}
}
This is my code so far, and I'm pretty sure it's all I need, but the compiler is throwing the error:
'Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String'
I've tried playing around with the System.out line a few times but I can't figure out where I'm going wrong!
Any ideas? Thanks in advance :)
Upvotes: 0
Views: 69
Reputation: 159784
p + " and your area is %.3f"
is being interpreted as a String
due to type promotion. Use
System.out.format("Your perimeter is %.3f and your area is %.3f", p, a);
Upvotes: 5
Reputation: 2188
System.out.format("Your perimeter is %.3f and your area is %.3f", p, a);
The reason is because the format method expects the first arg to be the format string followed by a varargs of objects to printed. You were passing a string as the second argument and you were trying to format it as a float, which caused the exception to be thrown.
Upvotes: 3