Reputation: 1
I'm having a problem with printf. I want to print out two sepreate arrays of doubles and limit the decimal place to one, but I am getting an error. The first array will print with the temperatures in celsius and the second array will obtain these values and change them into Farenheit, which will also be printed to the screen. I'm trying to implement the printf method when the numbers are getting printed out. The only problem I can think of is that I am referencing an index value in the array and not actually a double.
import java.util.Scanner;
public class tempOne {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
double [] temp1 = new double [10];
double [] temp2 = new double[10];
System.out.println("Please enter 10 temperatures in Celsius: ");
for (int index = 0; index<temp1.length;index++)//Gets temperatures in Celsius.
{
temp1[index]=sc.nextDouble();
}
for (int index = 0; index<temp1.length;index++)//Prints temperatures in Celsius.
{
System.out.printf("Temperatures in Celsius: %.1f", temp1[index] + " ");
}
for (int index = 0; index<temp1.length;index++)//Copies array 1 into array 2.
{
temp2[index]=temp1[index];
}
System.out.println("");
for (int index = 0; index<temp1.length;index++)//Changes values in array 2 to Farenheit.
{
temp2[index] = ((temp1[index]*9/5)+32);
}
for (int index = 0; index<temp1.length;index++)
{
System.out.printf("Temperatures in Farenheit: %.1f", temp2[index] + " ");//Prints array 2.
}
}
}
And here is the result:
Please enter 10 temperatures in Celsius:
20.22
Temperatures in Celsius: Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2806)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2753)
at java.util.Formatter.format(Formatter.java:2520)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at tempOne.main(tempOne.java:16)
Anyone have any ideas of what's going on here?
Upvotes: 0
Views: 99
Reputation: 4462
You want to format double and you pass String parameter instead. Try (remove + ""
):
System.out.printf("Temperatures in Farenheit: %.1f", temp2[index])
Upvotes: 2
Reputation: 11028
Remove the + " "
at the end of your printf
s.
The %.1f
means "print a float value with one decimal place", but with the + " "
you're converting that number into a String
.
Upvotes: 2