LearnFrenzy
Sign in Take a free test

Java Basics, Syntax and Data Types · Java Basics Programs · Question 2

Celsius to Fahrenheit and Kelvin table in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Print a table of Celsius temperatures from -10 to 40 in steps of 10 with their Fahrenheit and Kelvin values, aligned in columns.

Solution
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.printf("%8s%12s%10s%n", "Celsius", "Fahrenheit", "Kelvin");
        for (int c = -10; c <= 40; c += 10) {
            double f = c * 9.0 / 5 + 32;          // 9.0 avoids integer division
            double k = c + 273.15;
            System.out.printf("%8d%12.1f%10.2f%n", c, f, k);
        }
    }
}

Output Verified by compiling and running

 Celsius  Fahrenheit    Kelvin
     -10        14.0    263.15
       0        32.0    273.15
      10        50.0    283.15
      20        68.0    293.15
      30        86.0    303.15
      40       104.0    313.15

Writing c * 9 / 5 would use integer division and give wrong values for many temperatures; 9.0 makes the expression double.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links