FahrToCelsius
Java is not just used for the World Wide Web. The next program demonstrates a classic use of computers that goes back to the earliest punch card machines. It’s reminiscent of some of the very first useful programs I ever wrote. These were designed to quickly calculate several dozen numbers to keep me from having to do them by hand in physics lab. It’s also borrowed directly from Kernighan and Ritchie.
// Print a Fahrenheit to Celsius table
class FahrToCelsius {
public static void main (String args[]) {
int fahr, celsius;
int lower, upper, step;
lower = 0; // lower limit of temperature table
upper = 300; // upper limit of temperature table
step = 20; // step size
fahr = lower;
while (fahr <= upper) { // while loop begins here
celsius = 5 * (fahr-32) / 9;
System.out.print(fahr);
System.out.print(" ");
System.out.println(celsius);
fahr = fahr + step;
} // while loop ends here
} // main ends here
} //FahrToCelsius ends here
This program calculates the Celsius equivalent of Fahrenheit temperatures between zero and three hundred degrees. The first two lines of the main method declare the variables we’ll use. That is they specify the names and the types. For now we use only integers. In Java an int
can have a value between -2,147,483,648 to 2,147,483,647. More types will be forthcoming.
Then we initialize the variables using statements like “lower = 0
“. This sets lower
’s initial value to 0. When used this way the equals sign is called the assignment operator.
After establishing the initial values for all our variables we go into the loop which does the main work of our program. At the beginning of each iteration of the loop (fahr <= upper)
checks to see if the value of fahr
is in fact less than or equal to the current value of upper
. If it is then the computer executes the statements in the loop block (everything between “while loop begins here” and “while loop ends here”.) Loops in Java are marked off by matching pairs of braces and may be nested.
celsius = 5 * (fahr-32) / 9;
actually calculates the Celsius temperature given the fahrenheit temperature. The arithmetic operators here do exactly what you’d expect. * means multiplication. – is subtraction. / is division; and +, though not used in here, is addition. Precedence follows normal algebraic conventions, and can be rearranged through parentheses.
Java contains an almost complete set of arithmetic operators. Like C it is missing an exponentiation operator. For exponentiation you need to use the pow methods in the java.lang.Math package.
Printing output is very similar to what you’ve seen before. We use System.out.print(fahr)
to print the fahrenheit value, then System.out.print(" ")
to print a one-character string containing a space, and finally System.out.println(celsius);
the Celsius value.
Finally we increment the value of fahr
by step
to move on to the next value in the table.