
CIS 120 Lab 2
Spring 2007
Objectives:
(A) to expose students to more Java code, in the case of program A, one that uses class
methods other than main. The example code given has arguments to the methods and
has a return value.
(B) To expose students to more Java code, in the case of program B, one that uses the various
8 primitive data types supported by Java.
Students are to type Programs A and B (class definitions for ConvertTemperatures and
PrimitiveTypes) in using JGrasp and to debug the code as needed to get it to actually run.
Program A: call this file ConvertTemperatures.java. Line numbers should not be entered, they
are shown here only for discussion purposes.
1. // Author : <Your Name>
2. // Identification : CIS 120 Lab 2
3. // Note : For lab brevity usual global documentation left off.
4. // Imported Packages/Classes
5. import javax.swing.*; // Gets us JOptionPane!
6. class ConvertTemperatures {
7. // A utility method to prompt user for a fahrenheit or centigrade value and then
8. // to convert that String to a float value to return. Note: this method does not
9. // do error checking (if user enters "hello" it bombs).
10. public static float getTemperature(String temperatureName) {
11. String temperatureString;
12. float temperature;
13.
14. temperatureString = JOptionPane.showInputDialog("Enter " + temperatureName +
15. " value: ");
16. temperature = Float.parseFloat(temperatureString); // No error check!
17. return temperature;
18. } // getTemperature
19. // A conversion method to convert temperatures in either direction.
20. public static float convert(boolean centigradeToFahrenheitWanted,
21. float temperature) {
22. float answer;
23 if (centigradeToFahrenheitWanted)
24. answer = (9.0f*temperature)/5.0f + 32.0f;
25. else // Convert fahrenheit to centigrade!
26. answer = 5.0f*(temperature - 32.0f)/9.0f;
27. return answer;
28. } // convert
29. public static void main (String[] args) {
30. // Local Variables :
31. String whichConversion = "";
32. String output = "";
33. float userInputFloat;