Issue
I'm trying to write a Java program that converts Celsius to Fahrenheit. I want the output to print values to one decimal place.
The program should prompt the user the question: "Enter a temperature in degrees Celsius"
And then output their answer like these examples: 50.0 C = 122 F or 40.5 C = 104.9 F
I'm trying to use the printf() method, but I'm unable to get my answer to end with F to represent Fahrenheit.
My code:
Scanner in = new Scanner(System.in);
System.out.print("Enter a temperature in degrees Celsius ");
double celsius = in.nextDouble();
double fahrenheit = 9.0 / 5 * celsius + 32;
System.out.printf(celsius + " C = " + "%.1f\n", fahrenheit + " F");
When I run the program my output is missing the F that I need at the end. Answers print like:
40.5 C = 104.9
Any advice would be appreciated. Thank you.
Solution
With printf
you want to have a format string, then the items to include in it.
System.out.printf("%.1f C = %.1f F\n", celsius, fahrenheit);
The format specifiers (in this case %.1f
) say where to insert those values into the string, but also how to format them.
You should not find yourself concatenating together the format string. The point of printf
is to provide a way to insert data into a string to print.
Answered By - Chris
Answer Checked By - David Marino (JavaFixing Volunteer)