I’m stuck at the printf
statement. Can anyone tell, what’s the right syntax for printf
when formatting a double
?
JavaScript
x
public static void main(String[] args){
System.out.printf("%-15s %-5s" + " | " + "%5s %15s n", "Celcius", "Fahrenheit", "Fahrenheit", "Celcius");
for(double celcius = 40, fahrenheit = 120; celcius >= 31 && fahrenheit >= 30; celcius--, fahrenheit--){
System.out.printf("%.1-15f%.1-5f|%.115f%.115fn", celcius, celciusToFahrenheit(celcius), fahrenheit, fahrenheitToCelcius(fahrenheit));
}
}
public static double celciusToFahrenheit(double celcius){
double fahrenheit = (9.0 / 5) * (celcius + 32);
return fahrenheit;
}
public static double fahrenheitToCelcius(double fahrenheit){
double celcius = (5.0 / 9) * (fahrenheit - 32);
return celcius;
}
Advertisement
Answer
These are the System.out.printf()
format rules:
JavaScript
%[flags][width][.precision]conversion-character
You can find plenty of examples and explanation of printf()
here and here