Java Project: Temperature Conversion

Tips :: JavaJava code for the conversion of degrees from Celsius to Fahrenheit and vise versa. This was a project for Java programming 101 in the fall semester of 2012. The project and tutorial can help Java newbies get a sense of some of the basic conditions and loops.

 

 

Copying this project in full or in part is plagiarism. I share this code as a sample, to help you understand and learn. If you use any of this code, you should maintain the attribution to the original author (me!) along with a link to this page.

The Exercise

The original project exercise stated:

Write a program that allows the user to convert a temperature given in degrees from either Celsius to Fahrenheit or Fahrenheit to Celsius. Use the following formulas:
Degrees_C = 5(Degrees_F-32)/9
Degrees_F = (9(Degrees_C)/5) + 32)
Prompt the user to enter a temperature and either a C or c for Celsius or an F or f for Fahrenheit. Convert the temperature to Fahrenheit if Celsius is entered or to Celsius if Fahrenheit is entered. Display the result in a readable format. If anything other than C, c, F, or f is entered, print an error message and stop.

My code goes a bit further than that, but the principle remains the same.

Algorithm Description

We start by setting up the variables and strings that would be needed in the code:

float convertedResult = 0, valueTemperature=0;
String typeTemperature = "", fullInput = "";
int counter = 0;

These variables and strings will be used in the rest of the class to define and manipulate the output.

Next, we ask the user for input. For convenience, since we will repeat this request for input later, the request is served through the function speakIntroduction(). If we wish to change the request, we will only have to change the function rather than changing it over and over in the repetitive code:

/**
 * Prints the introduction text.
 */
public static void speakIntroduction () {
    System.out.println(""); 
    System.out.println("Please enter a temperature to convert.");
    System.out.println("Enter C/c for celsius or F/f for Fahrenheit");
    System.out.println("(Examples: 100C, 32f)\n"); 
    return;
}

This function merely prints out the instruction on the screen. It will be repeated every 5 attempts by the user as a usage reminder.

The program will request input from the user, on a continuous loop. The user will be prompted to provide input until they enter either “stop” or “quit”.

Scanner keyboard = new Scanner (System.in);
while ((!fullInput.equals("quit")) && (!fullInput.equals("stop"))) {
...
    /* Collect Input */
    System.out.println("");
    System.out.println("To quit, enter 'quit' or 'stop'.");
    System.out.print("Temperature to convert: ");
    fullInput = keyboard.nextLine();
...
}

Trim Whitespaces

The lowercase action is meant to make sure the entire code validates on the same condition without worrying about case sensitivity. This will be useful for the temperature type (‘c’ or ‘C’) and to the stop commands (‘stop’ or ‘STOP’ or ‘Stop’, etc).

(Notice that this can also be done by requesting a comparison regardless of case by using the method equalsIgnoreCase)

fullInput.trim();
fullInput = fullInput.toLowerCase();

Verify String is not Empty

if (fullInput.length() <=0) 
    continue;

Manipulate the String

Split the string to numerical temperature and temperature type (symbol):

typeTemperature = fullInput.substring(fullInput.length()-1);
/* Verify that requested temperature is numeric (float) */
try {
    valueTemperature = Float.parseFloat(fullInput.substring(0,fullInput.length()-1));
} catch(NumberFormatException nfe) {
    if ((!fullInput.equals("quit")) && (!fullInput.equals("stop"))) 
        System.out.println("Please specify a numerical temperature.");
    continue;
}

As it splits the input, the program verifies that the first part is a number (float). If there are no numbers in the supplied input, an error message will be printed and the loop will restart, asking the user to re-enter the input.

Since the user can also type “stop” or “quit” to stop the program, either of those will match the exception caught in the NumberFormatException. However, these should not produce the same error message, but instead continue to the output processing phase, and so these will be skipped, and the loop will stop.

Calculate Output

After the previous step, the program produces two variables that were split from the original input.

calculateOutput(typeTemperature, valueTemperature);

These will be calculated for a proper output using the boolean function calculateOutput():

public static void calculateOutput (String typeOfTemperature, float valueOfTemperature) {
    String resultConvert = "", resultType = "";
    float convertedResult = 0;
    typeOfTemperature = typeOfTemperature.toLowerCase();

    if (typeOfTemperature.equals("c")) {
        /* convert to fahrenheit */
        convertedResult = 9 * valueOfTemperature /5 +32;
        resultConvert = " Celsius ";
        resultType = " Fahrenheit ";
    } else if (typeOfTemperature.equals("f")) {
        /* convert to celsius */
        convertedResult = 5*(valueOfTemperature - 32)/9;
        resultConvert = " Fahrenheit ";
        resultType = " Celsius ";
    } else {
        System.out.println("Please specify C(celsius) or F(fahrenheit). Example: 32F or 100C");
        return;
    }
    /* Display Output */
    System.out.println(""); 
    System.out.println(valueOfTemperature + resultConvert + "is " + convertedResult + resultType);
    return;
}

The function checks the character value of the type of temperature and uses it to calculate output. If the temperature given is in Fahrenheit, the program will convert to Celsius and return the outputted result:

convertedResult = 9 * valueOfTemperature /5 +32;

If the temperature is given in Celsius, the program will convert to Fahrenheit and return the outputted result:

convertedResult = 5*(valueOfTemperature - 32)/9;

Otherwise, the program will return an error:

System.out.println("Please specify C(celsius) or F(fahrenheit). Example: 32F or 100C");

Following this, the loop returns and the user is asked to provide the input again, or insert ‘quit’ or ‘stop’ to quit the program.

Repeating Instructions

In order to remind the user about the purpose of the program, the initial instructions will be printed on the screen every 5 input attempts. The counter will be reset and count 5 input loops again:

counter++;
if (counter > 5) {
    /* Every 5 occurences, remind the user of the introduction */
    speakIntroduction();
    counter = 0;
}

Exiting

Finally, when the user inputs “quit” or “stop”, the loop will end, and so will the program:

/* END */
System.out.println(""); 
System.out.println("Thank you!");

Output

Click to Enlarge

Click to Enlarge

The Full Code

Please note: You are free to use this class in your code, as long as you keep the attribution and copyright notice. If you improve it, send it back to me and I’ll make sure to credit your improvements in the live version!
/**
 * A program to convert temperature from Fahrenheit to Celsius and vise versa.
 * @author Moriel Schottlender
 * @version 1.0
 *
 * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported
 * http://creativecommons.org/licenses/by-nc-sa/3.0/
 */
import java.util.Scanner;
public class TemperatureConvert {
    public static void main (String [] args) {
        /* Set up variables */
        float valueTemperature=0;
        String typeTemperature = "", fullInput = "";
        int counter = 0;

        /* Ask for input */
        speakIntroduction();
        Scanner keyboard = new Scanner (System.in);

        while ((!fullInput.equals("quit")) && (!fullInput.equals("stop"))) {
            counter++;
            if (counter > 5) {
                /* Every 5 occurences, remind the user of the introduction */
                speakIntroduction();
                counter = 0;
            }
            /* Collect Input */
            System.out.println("");
            System.out.println("To quit, enter 'quit' or 'stop'.");
            System.out.print("Temperature to convert: ");
            fullInput = keyboard.nextLine();

            /* Parse Input */
            fullInput.trim();
            fullInput = fullInput.toLowerCase();

            //verify the string is not empty:
            if (fullInput.length() <=0) 
                continue;

            typeTemperature = fullInput.substring(fullInput.length()-1);
            /* Verify that requested temperature is numeric (float) */
            try {
                valueTemperature = Float.parseFloat(fullInput.substring(0,fullInput.length()-1));
            } catch(NumberFormatException nfe) {
                if ((!fullInput.equals("quit")) && (!fullInput.equals("stop"))) 
                    System.out.println("Please specify a numerical temperature.");
                continue;
            }
            /* Calculate Output */
            calculateOutput(typeTemperature, valueTemperature);
        }

        /* END */
        System.out.println(""); 
        System.out.println("Thank you!");

    }

    /**
     * Prints the introduction text.
     */
    public static void speakIntroduction () {
        System.out.println(""); 
        System.out.println("Please enter a temperature to convert.");
        System.out.println("Enter C/c for celsius or F/f for Fahrenheit");
        System.out.println("(Examples: 100C, 32f)\n"); 
        return;
    }

    /**
     * Calculates and outputs the converted temperature based 
     * on the parameters received by the user.
     *
     * @param typeOfTemperature   Temperature type, expects
     *                            C or c for Celsius, or 
     *                            F or f for Fahrenheit.
     * @param valueOfTemperature  Temperature value, expects
     *                            numerical representation (float)
     * @return boolean            returns TRUE if output caculated
     *                            successfully. FALSE otherwise.
     *
     */
    public static void calculateOutput (String typeOfTemperature, float valueOfTemperature) {
        /* expected input: calculateOutput(typeTemperature, valueTemperature) */
        /* output 'true' if type is F/f/C/c, otherwise return false */
        String resultConvert = "", resultType = "";
        float convertedResult = 0;

        if (typeOfTemperature.equals("c")) {
            /* convert to fahrenheit */
            convertedResult = 9 * valueOfTemperature /5 +32;
            resultConvert = " Celsius ";
            resultType = " Fahrenheit ";
        } else if (typeOfTemperature.equals("f")) {
            /* convert to celsius */
            convertedResult = 5*(valueOfTemperature - 32)/9;
            resultConvert = " Fahrenheit ";
            resultType = " Celsius ";
        } else {
            System.out.println("Please specify C(celsius) or F(fahrenheit). Example: 32F or 100C");
            return;
        }
        /* Display Output */
        System.out.println(""); 
        System.out.println(valueOfTemperature + resultConvert + "is " + convertedResult + resultType);
        return;
    }

}

 

Tags: ,

Trackback from your site.