Docsity

Java Lab 2: Temperature Conversion and Primitive Data Types - Prof. Derek B. Snow, Lab Reports of Computer Science

Toggle sidebar
bg1
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;
pf3
pf4
pf5

Partial preview of the text

Download Java Lab 2: Temperature Conversion and Primitive Data Types - Prof. Derek B. Snow and more Lab Reports Computer Science in PDF only on Docsity!

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 :
  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. temperatureString = JOptionPane.showInputDialog("Enter " + temperatureName +
  14. " value: ");
  15. temperature = Float.parseFloat(temperatureString); // No error check!
  16. return temperature;
  17. } // getTemperature
  18. // A conversion method to convert temperatures in either direction.
  19. public static float convert(boolean centigradeToFahrenheitWanted,
  20. float temperature) {
  21. float answer; 23 if (centigradeToFahrenheitWanted)
  22. answer = (9.0f*temperature)/5.0f + 32.0f;
  23. else // Convert fahrenheit to centigrade!
  24. answer = 5.0f*(temperature - 32.0f)/9.0f;
  25. return answer;
  26. } // convert
  27. public static void main (String[] args) {
  28. // Local Variables :
  29. String whichConversion = "";
  30. String output = "";
  31. float userInputFloat;
  1. // Query user as to which conversion he wants.
  2. whichConversion = JOptionPane.showInputDialog(“(A) convert centigrade to” +
  3. “fahrenheit or (B) convert fahrenheit to centigrade? ");
  4. whichConversion = whichConversion.toUpperCase(); // convert "a" to "A".
  5. if (whichConversion.equals("A")){
  6. userInputFloat = getTemperature("centigrade");
  7. output = userInputFloat + " degrees in centigrade = " +
  8. convert(true,userInputFloat) + " degrees fahrenheit.";
  9. }
  10. else if (whichConversion.equals("B")) {
  11. userInputFloat = getTemperature("fahrenheit");
  12. output = userInputFloat + " degrees in fahrenheit = " +
  13. convert(false,userInputFloat) + " degrees centigrade.";
  14. } 49 else { // Bad input by user.
  15. output = "Sorry, you were supposed to enter an 'A' or a 'B'.";
  16. }
  17. JOptionPane.showMessageDialog(null, output, "Temperature Conversion",
  18. JOptionPane.PLAIN_MESSAGE);
  19. System.exit(0);
  20. } // main
  21. } // ConvertTemperatures

Call program B below PrimitiveTypes.java.

  1. // Author :
  2. // File : PrimitiveTypes.java
  3. // Imported Packages/Classes
  4. import javax.swing.*; // To import JOptionPane.
  5. class PrimitiveTypes {
  6. public static void main (String[] args) {
  7. // Local Variables :
  8. // Java supports 8 primitive data types and objects.
  9. // Testing 4 integer primitive data types:
  10. byte aByte; // 1 byte long roughly -127 to +
  11. short aShort; // 2 bytes long roughly -32,000 to + 32,
  12. int anInt; // 4 bytes long roughly -2 billion to + 2 billion
  13. long aLong; // 8 bytes long roughly -2 to the 63 power to + 2 to the 63rd
  14. // Testing 2 (real number) data types: - with fractional parts.
  15. float aFloat; // 4 bytes - good for about 7 decimal digits of precision
  16. double aDouble; // 8 bytes - wider "range" and more digits of precision
  17. // namely about 15 decimal digits worth.
  18. // Testing remaining two Java primitive data types:
  19. boolean aBoolean; // 1 byte (set to "true" or "false")
  20. char aChar; // 2 bytes based on Java Unicode! (old style 1 byte ASCII)
  21. // Other data items must be objects of various types that we usually create
  22. // using a call to "new". One VERY commonly used object class is String.
  23. String myName = new String("Joe Blow");
  24. String yourName = "Jane Doe"; // Short form of above line.

Explanation of Lab 2 Code

Students, please note that as you read over this explanation that there will be things here that you

may understand and some that you do not yet understand. Do NOT WORRY about this.. this is

just a first exposure. Take a shot at reading it and understanding it… but know that ALL of the

points made here will be repeated as we move forward into CIS 120.

Program A : ConvertTemperatures.java

 The file name ConvertTemperatures.java should match (exactly) the class name in the

file “ConvertTemperatures”. The class name of course should follow standard coding

conventions of having the first letter of each word capitalized.

 Line 5 could also have been “import javax.swing.JOptionPane;”

 Lines 10 to 18 form a method other than the “main” method that we have been used to

writing. This method called “getTemperature” – which is consistent with our coding

conventions of having first word in lowercase and subsequent words capitalized. This

method is actually called from our “main” method – lines 29 to 55. We see this method

being called on line 40 and 45 of main.

 Line 10, the header for the getTemperature method, has a “float” in it to indicate that

when this method is finished that it will be returning a float (think real number with a

fractional part) to the point where the method was called. On line 12 we have a local

variable that we use to compute and hold the value to be returned. On line 17 we say to

return the float value held in “temperature”.

 In line 10 we see that this method will be “receiving” an incoming parameter of type

String that we will refer to as “temperatureName”. The line that calls this method (40 or

45) will supply a value for temperatureName in the call itself. In line 40 this argument is

sent in as “centigrade” and in line 45 it is sent in as “Fahrenheit”.

 The intent of the getTemperature method is to prompt the user to enter a temperature of a

given “type” and then to return a float after we convert what the user enters from a String

to a float (line 16 performs that String to float conversion for us).

 Lines 20 to 28 form another utility method called “convert”. The purpose of this method

is to convert the given float parameter (called “temperature”) from centigrade to

Fahrenheit or from Fahrenheit to centigrade. The first Boolean parameter tells us which

conversion to make. If that Boolean is “true” then the method converts centigrade to

Fahrenheit. If that Boolean parameter is “false” then the method convert the temperature

from Fahrenheit to centigrade. The “float” in the header on line 20 tells us that this

method will return a computed float value to the caller (lines 42 and 47 of main).

 Lines 36 and 37 of main show a JOptionPane being used to offer the user a menu

choice… “A” for Centigrade to Fahrenheit and “B” for Fahrenheit to centigrade. The

user will hopefully type in an A or a B (though he might do so using lowercase).

 On line 38 we convert the String entered by the user to uppercase letters before we check

what he entered. Thus we need only look for “A” not “A” or “a”.

 On line 39 we check to see if the user responded to our menu choice with an “A” or not.

If so, we execute lines 40, 41 and 42. If not, we check to see if the user entered a “B” (or

“b”) to our menu choice. If so, we execute lines 45 to 47. If not, then the user typed in

an illegal choice so we form an error message (line 50) to show in the output window.

 On line 52 we display the converted values (or an error message). Note that we do catch

and report on the error of an illegal menu choice being entered (i.e., not an A or B), but

we do not “handle” an input error of bad numeric input. When we ask the user to input a

Fahrenheit number if he enters “hello” instead our program will just bomb! In particular,

it would bomb at line 16 where that conversion from String to float is being performed.

Comments on Program B:

 Program B shows declarations for variables of each of the eight primitive data types

supported by Java. Four of those data types are used to hold integer values like … -2, -1,

0, 1, 2, etc. Those four integer data types are: byte , short , int and long. Those 4 data

types use main memory space that differs with each type: byte = 1 byte of main memory

(recall 8 bits), short = 2 bytes, int = 4 bytes, long = 8 bytes. As a result of the different

bit lengths for each of these data types they have different ranges of values they can hold.

Recall that N-bits can be used to represent 2N^ different values. Thus the byte data type

(with 8 bits) can represent only 2^8 different numbers (i.e., 256 different numbers). Since

some of those numbers will be negatives, the byte data type can only hold values from

about -127 to +127. The int data type on the other hand uses 4 bytes of main memory

storage (i.e. 32 bits) so it can represent 2^32 different numbers, roughly half of which are

used for negative numbers, hence the int data type can represent numbers from roughly -

231 to + 2^31. Similarly, the long data type (64 bits each) can be used to represent numbers

from roughly -2^63 to +2^63.

 In addition to the four integer data types described above, two Java primitive data types

are used to hold real numbers with fractional parts to them (e.g. 3.14). The two Java data

types used to hold real numbers are float and double. These two data types each have

their range to them [i.e. the largest negative/positive number that they can each represent]

and they have their “precision” which is how many digits that they are able to accurately

keep up with. Double has a wider range than float and has greater precision as well. The

float data type can keep up with about 7 decimal digits of accuracy (after that things get

rounded off). Double on the other hand can keep up with almost 15 decimal digits of

precision. This makes us think “then let me always use double not float”… but part fo

the “penalty” for using double is the extra space needed and slower computations.

 The final two primitive Java data types are: boolean and char. Boolean variables are

used to hold values like “true” and “false”. Char variables are used to hold data like ‘A’,

‘a’, or ‘$’ [note use of single quotes around char constants – not double quotes!] In the

early days of computers, char variables would get one byte of storage (so there were only

256 = 2^8 different characters possible). The ASCII (American Standard Code of

Information Interchange) table specified EXACLTY which letter mapped to which of the

possible 256 bit patterns (e.g. ‘A’ = ‘01000001’). However, this proved for other

languages to be too constraining! We needed bit patterns for more than a meager 256

different character. Solution: Unicode (used by Java). In Unicode we give 2 bytes (

bits) to each character, thus we can handle 2^16 (65,536) different characters with it.

 All data in Java is either one of the eight primitive data types or is an object. An object is

an instance of some class. Class names in Java are spelled with a capital letter. The

String that you have seen used so far is an example of a class name. A particular string

is an object (of type String). In most cases in Java objects are “created” using the Java

keyword new. Line 23 shows the creation of a String object called myName using new.