Converting Temperatures in Java
Submitted by GeePee on Monday, May 11, 2015 - 23:26.
This tutorial covers creating a calculator to convert between Celsius (centigrade), Kelvin, and Fahrenheit. The user is first given the choice of which temperature unit they would like to convert from, and then they are given the results of the conversion.
When different units are in use, things can get confusing. It is useful to have a calculator on hand for this sort of thing. Luckily, we can make one in Java that is able to do just that. Let's get right into the code.
As you can see, there is a decent amount of code dealt with here. However, it is nicely organized into four separate methods. This is where separate methods begin to really come in handy for organization. We have a main method, where the user makes their selection, and then three other methods for performing calculations; the method that is called depends upon the user's choice.
It is always useful to avoid errors to add code for what wouldn't be considered a valid input. In this case, we have
This is the final else, only executing if neither the if nor the else ifs were satisfied.
- import java.util.Scanner;
- public class temps
- {
- public static double c, k, f; //creates public variables for use in all methods
- {
- System.out.println("\nPlease enter the number of the temperature you would like to convert from:\n\n1 - Celsius\n2 - Kelvin\n3 - Fahrenheit\n");
- double userChoice = input.nextDouble();
- input.nextLine();
- if (userChoice == 1) //calls respective methods depending on user input
- celsius();
- else if (userChoice == 2)
- kelvin();
- else if (userChoice == 3)
- fahrenheit();
- else //closes program if user does not enter a 1, 2, or 3
- {
- }
- }
- public static void celsius()
- {
- c = input.nextDouble();
- k = c + 273 + 0.15;
- f = c * 9/5 + 32;
- System.out.println("\n" + c + " Celsius is equal to " + k + " degrees Kelvin and " + f + " degrees Fahrenheit.");
- }
- public static void kelvin()
- {
- k = input.nextDouble();
- c = k - 273.15;
- f = c * 9/5 + 32;
- System.out.println("\n" + k + " Kelvin is equal to " + c + " degrees Celsius and " + f + " degrees Fahrenheit.");
- }
- public static void fahrenheit()
- {
- f = input.nextDouble();
- c = (f - 32) * 5/9;
- k = c + 273 + 0.15;
- System.out.println("\n" + f + " Fahrenheit is equal to " + c + " degrees Celsius and " + k + " degrees Kelvin.");
- }
- }
Add new comment
- 50 views