import java.util.Scanner; /* Java application that produces a Fahrenheit-to-Celsius conversion table. ** The user provides as input (via the keyboard) the floor and ceiling ** Fahrenheit temperatures and the "delta" (the amount by which each line's ** Fahrenheit temperature exceeds that of the previous line). ** (This version improves upon the previous one by making better use of ** methods. In particular, a method that produces the table is introduced, ** as is one that prompts the user for an input of type double and returns ** the user's response.) ** ** Author: R. McCloskey ** Date: March 2015 */ public class FahToCel4 { // Create a new Scanner object that can read input from the keyboard. // By being declared here (outside any method), this variable becomes // "global", meaning that its scope is the entire class. private static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { // Declare the input variables double fahFloor; // first Fah. temp. in the table double fahDelta; // increase in Fah. temp. from one row to next double fahCeil; // upper bound on Fah. temp.'s in the table // For each input, prompt the user and read it. fahFloor = getDoubleResponse("Enter starting Fahrenheit temp: "); fahDelta = getDoubleResponse("Enter Fahrenheit delta: "); fahCeil = getDoubleResponse("Enter Fahrenheit ceiling: "); // Produce the table. printTable(fahFloor, fahDelta, fahCeil); } /* Displays the specified prompt, reads the user's response (using ** the global Scanner object, keyboard), converts it to a value of ** type double, and returns that value to the caller. */ private static double getDoubleResponse(String prompt) { System.out.print(prompt); // Display the prompt. return keyboard.nextDouble(); // Read response and return it. } /* Prints the Fahrenheit-to-Celsius conversion table, where the first ** row's Fah. temp, the increase in Fah. temp from one row to the next, ** and the ceiling Fah. temp. are provided via the parameters. */ private static void printTable(double fLow, double fDelta, double fHigh) { // Print column headings. System.out.println("Fahrenheit Celsius"); System.out.println("---------- ---------"); // Produce the body of the table. Each loop iteration produces // a single row. for (double fah = fLow; fah <= fHigh; fah = fah + fDelta) { double celTemp = fahToCel(fah); System.out.println(fah + "F " + celTemp + "C"); } } /* Returns the Celsius equivalent of the given Fahrenheit temperature (f). */ private static double fahToCel(double f) { return (5.0 / 9.0) * (f - 32); } }