T. Andrew Yang

Email: yang@uhcl.edu

Web page : http://sce.uhcl.edu/yang/

Tel.: (281) 283-3835

last updated:

 

July 19, 2011

 

CSCI 3134 Java



  • Lab 1

Total points= 100

1.1. (10 pts) Visit the class discussion group at http://groups.google.com/group/csci3134-group-summer-2011 and request to join the group. Your request needs to be approved by the instructor first. Once it is approved, visit the group and complete the following tasks:

1.1.1.    Configure your membership settings, so each email sent to the group will be forwarded to your email address.

1.1.2.    Post a message with your full name as the subject line. In your post, briefly introduce yourself (including your full name) and one item you most desire to learn in this class.

1.1.3.    Throughout this class, you shall regularly visit the discussion group to find recent announcements and reminders, and to participate at discussions. 

1.2.   Java Development Environments: JDK

1.2.1.    Figure 1 shows a sample Java application.

-      Required sections in your program

Please note that all programs that you develop for this class should have the following sections:

a)   The program’s name

b)   The author’s name (that’s you)

c)   The date the program was written

d)   A brief description of the purpose of that program

e)   The compilation and execution commands

f)    Proper formatting including consistent indentations and appropriate comments

Note: See exercise 1.3 (below) for more information about the Java code conventions.

To download the source program as shown in Figure 1, click this link.

/* Program name: IntArrayTest2.java

 * Author: T. Andrew Yang

 * Date: June 6, 2011

 */

 

/* Description: This is a test program for implementing an integer array.

 * A user-defined constructor, IntArrayTest2(), is used to assign data to A[].

 */

 

/* Compilation command: javac IntArrayTest2.java

 * Execution command: java IntArrayTest2 -14

 */

 

public class IntArrayTest2 {

 

    // attributes

    private final int SIZE = 10;

    private int A[] = new int[SIZE]; // The array needs to be initialized

    private int currentPosition = 0;

 

    // methods

    public IntArrayTest2() {

        //System.out.println(“length: “ + A.length);

        for (; currentPosition < A.length; currentPosition++) {

            A[currentPosition] = 2 * currentPosition + currentPosition – 20;

        }

        //return; // do not place a return here

    }

 

    public int search(int key) {

        for (int i = 0; i < A.length; i++) {

            System.out.println(A[i]);

            if (A[i] == key) {

                return i;

            }

        } //for

        return -1; //not found

    } //search()

 

    // main( )

    public static void main(String args[]) {

        IntArrayTest2 ar = new IntArrayTest2();

        int key = Integer.parseInt(args[0]);

        //the value to search for, input from command line

 

        System.out.println("My name is XYZ.");

        int result = ar.search(key);

        System.out.println(“result: “ + result);

        if (result == -1) {

            System.out.println(key + “ is not in the array.”);

        } else {

            System.out.println(key + “ is stored at position “ + result + “.”);

        }

    } //main()

} // IntArrayTest2 class

Figure 1. A sample Java application

1.2.2.    Figure 2 is a screen snapshot that shows commands used to compile and execute the program, and the sample output produced by the program.

sampleRun.JPG

Figure 2. Running the sample Java application

1.2.1.    Save the sample program in Figure 1 as a text file (with IntArrayTest2.java as the file name). Remember where you have saved it.

1.2.2.    Revise the program by changing the string "My name is XYZ" to be your own name. Be sure to save the revised program.

1.2.3.    On a computer with Java Development Kit (JDK) properly installed, open a command prompt to run the revised program.

Note: You are strongly encouraged to install JDK on your own computer. Visit http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u25-download-346242.html to download the installation package and instructions. However, not being able to install the JDK on your own computer should NOT be a reason to be late in submitting the lab. Computers in the PC labs should have JDK installed, and you may use them to complete this portion of the lab.

1.2.4.To hand in:

a)                (10 pts) The revised Java source program.

b)               (10 pts) A screen snapshot of running the revised program in a command prompt using JDK.

c)                (20 pts) Give the TA a face-to-face demo during his office hours by showing how you’d run the revised program using JDK.

1.3.   Java Code Conventions

1.3.1.    Visit http://www.oracle.com/technetwork/java/codeconvtoc-136057.html to read the online document “Code Conventions for the Java Programming Language (Revised April 20, 1999)”. You will learn how to properly format a Java source program, effectively add comments to enhance comprehension, and other important issues in Java programming.

1.3.2.    Apply proper Java code conventions to reformat the program shown in Figure 3. Also refer to the sample program in Figure 1 to find a Java program that follows the code conventions.

 

To download the source program as shown in Figure 3, click this link.

 

public class IntArrayTest {

   // attributes

                private final int SIZE = 10;                  private int A[] = new int [SIZE];

        private int CurrentPosition  = 0;

               

   // methods

                public int size () {

                                return SIZE;

                } //size

 

public void add (int value) {

                        A[CurrentPosition++] = value;

                } //add()

 

public int search (int key) {

                         for (int i=0; i< A.length; i++) {

                                System.out.println (A[i]);

                                if (A[i] == key) return i;

                                } //for

                          return -1; //not found

} //search()

               

   // main( )

                public static void main (String args[] ) {

                                IntArrayTest3 ar = new IntArrayTest3 ();

 

                      for (int i=0 ; i < ar.size(); i++) {

                                ar.add(2*i + i - 20);

                      }

 

                                int Key = Integer.parseInt(args[0]);

                                //the value to search for, input from command line

 

                      int result = ar.search (Key);

                      System.out.println ("result: " + result);

                      if (result == -1)

                                                System.out.println (Key + " is not in the array.");

                                else

                                                System.out.println (Key + " is stored at position " + result + ".");

                }

} // IntArrayTest class

 

Figure 3. A sample Java program (with improper code conventions)

1.3.3.    To hand in:

a)   (15 pts) The revised program

b)   (15 pts) Select at least ten of the revisions you have made, and explain each of those revisions by quoting the code convention(s) you used for that revision.

c)   (20 pts) Give the TA a face-to-face demo during his office hours by showing how you’d run the revised program using JDK.

 

Go to the Index


  • Lab 2

Total points= 100

 

2.1.   Numbering Systems

2.1.1.    What is the decimal value of each of the following binary or hexadecimal numbers? Note: You may use a calculator to verify your answers, but be sure to show the intermediate steps that you used to derive the answer.

2.1.1.1.  (3 pts) 100101010b

2.1.1.2.  (3 pts) 10000001111b

2.1.1.3.  (3 pts) 123h

 

2.1.2.    What are the binary equivalents of the following decimal or hexadecimal numbers? Show the intermediate steps that you used to derive the answer.

2.1.2.1.  (3 pts) 12345d

2.1.2.2.  (3 pts) 100029d

2.1.2.3.  (3 pts) FC1Bh

 

2.1.3.    What are the hexadecimal equivalents of the following decimal or binary numbers? Show the intermediate steps that you used to derive the answer.

2.1.3.1.  (3 pts) 1234567d

2.1.3.2.  (3 pts) 10000001111b

 

2.2.   Chapter-end Exercises:

2.2.1.(6 pts, 1 pt each) Exercise 2.7: a, b, c, d, e, f

2.2.2.(4 pts, 1 pt each) Exercise 2.10: a, b, c, d

2.2.3.(2 pts) Exercise 2.12. Note: Choose all that are correct.

2.2.4.(4 pts, 2 pt each) Exercise 2.13: b, c

 

2.3.   Programming Projects

2.3.1.Exercise 2.33: Body Mass Index Calculator

2.3.1.1.    (20 pts) Program Design: Use a flow chart to show the flow of operations in your program.

2.3.1.2.    (20 pts) Program Implementation: Include the Java source program that you’ve written.

Note: Refer to the ‘Required sections in your program’ above when writing your source program. Missing section or inappropriate identifiers will reduce your earned grade.

2.3.1.3.    (20 pts) Program Verification: Compile and run your program using JDK and verify that the program behaves correctly. Attach three screen snapshots of testing your program. Give the TA a face-to-face demo during his office hours by showing how you’d run your program using JDK.

Go to the Index


  • Lab 3

Total points= 100

3.1.   (10 pts) A class called Person is defined in Figure 3.1. Draw a UML class diagram (using Microsoft Word, Visio, or any computer-based tool) to model the Person class.

public class Person {

  private String firstName;

  private String lastName;

  private int age;

 

  public String getFirstName() {

    return firstName;

  }

 

  public void setFirstName(String firstName) {

    this.firstName = firstName;

  }

 

  public String getLastName() {

    return lastName;

  }

 

  public void setLastName(String lastName) {

    this.lastName = lastName;

  }

 

  public int getAge() {

    return age;

  }

 

  public void setAge(int age) {

    this.age = age;

  }

 

} //class: Person

Figure 3.1: The class definition of Person

(Click this link to download the Java source file.)

 

3.2.   Class Customer: Revise the UML class diagram you have derived from the exercise above to create a new class called Customer, which represents a customer of a bank.

3.2.1.  (10 pts) Class Design: Each customer has the following attributes: firstName, lastName, middleName, dateOfBirth, customerNumber, and address. In addition to the typical set and get methods for each of these attributes, include an additional instance method age( ), which returns the age of the customer. Note: a person’s age = today’s date – that person’s date of birth.

3.2.2.  (10 pts) Class Implementation: Implement the Customer class using Java by defining the Customer.java source file.

3.2.3.  (20 pts) Driver Class: Define a driver class called CustomerTest to test drive the Customer class. In the driver class, create two customers: John Peter Doe and Jane Chong Wu. Use appropriate set methods to set the value of each of the instance variables. Use appropriate get methods to retrieve the values of a customer. Display both customers’ information on the screen. Give the TA a face-to-face demo during his office hours by showing how you’d run your program using JDK.

Note: There are two approaches for calculating the age of a customer.

Approach 1 (the easy approach): Use only the person’s birth year and the current year to calculate the age.

Approach 2 (more challenging but with bonus points): Use the Date or Calendar classes to calculate a person’s age. Those who successfully get this done will earn 30 additional points for this lab.

 

3.3.   (10 pts) Figure 3.15 in the book shows a class diagram for Account. Revise the Account class diagram by adding two additional attributes: owner (of type Customer) and accountType (of type int). Add corresponding set and get methods for the new attributes. Add an additional method called transfer( ), which takes three parameters:

The first parameter is of type Account, representing the account from which fund will be transferred.

The second parameter is of type Account, representing the account to which fund will be transferred.

The third parameter is of type float, representing the fund to be transferred.

 

3.4.    (10 pts) Draw a UML class diagram that includes both the Customer and the Account classes. Show appropriate association between the two classes. Note: A customer may have one or more accounts; an account is owned by one and only one customer.

3.4.1.(10 pts) Implement the Account class using Java by defining the Account.java source file. Save both Custome.java and Account.java into the same folder.

3.4.2.(20 pts) Define a driver class called AccountTest to test drive the Account class.

In the driver class, create two customers: John Peter Doe and Jane Chong Wu. Use appropriate set methods to set the value of each of the instance variables. Use appropriate get methods to retrieve the values of a customer.

Create the following accounts:

Account 1 is a checking account owned by John.

Account 2 is a saving account owned by both John.

Account 3 is a checking account owned by Jane.

Account 4 is a saving account owned by both Jane.

For each of the accounts, display the following information on the screen: account type, account balance, owner’s customer number, owner’s first name, owner’s last name, owner’s age, and owner’s address.

Give the TA a face-to-face demo during his office hours by showing how you’d run your program using JDK.

Note: The transfer( ) method in the Account class is not required to be implemented for this lab.

3.4.3.(10 bonus points) The transfer( ) method in the Account class: Those who successfully implement and demonstrate the transfer( ) method (see 3.3 above) will earn 10 additional points for this lab. Hint: The transfer( ) method may be implemented as a static method.

 

Go to the Index


  • Lab 4

Total points= 100

4.1.   NetBeans IDE

An integrated development environment (IDE) such as NetBeans provides additional functions for a programmer to develop software applications. As shown in Figure 4.1, NetBeans provides various options for a programmer to create a Java application. In this class, you shall learn to become familiar with at least two of those options:

(a) To create a Java application from the scratch (by choosing the ‘Java Application’ option when creating a new project);

(b) To create a Java application using existing source programs (by choosing the ‘Java Project with Existing Sources’ option.

To learn about NetBeans, take either (or both) of the following tutorials:

http://netbeans.org/kb/docs/java/quickstart.html   http://java.sun.com/developer/onlineTraining/tools/netbeans_part1/

 

NetBeansJava.JPG

Figure 4.1: NetBeans provides various options for a programmer to create a Java application

 

4.2.   (10 pts)  Use NetBeans to create a Java application from the scratch (option a above). The application should print a message like “"Hello! This is XYZ.” Replace XYZ by your full name. Give the TA a demo to show that you can do this. Your output screen should look like the one below.

 

netBeansOutput.JPG

 

4.3.   (10 pts) Download or save the program for Exercise 4.6 into a file. Use option b above (create a Java application using existing source programs) to run that program as a Java application.

Revise the program a bit so the output will look like the one below (a greeting with your full name + a more detailed message before printing the sum).

Give the TA a demo. Note: Do not create the program from the scratch. You may save the file into a new sub-folder.

Calculate.JPG

 

4.4.   Calculating the first N natural numbers

Revise the Calculate program by getting a number from the user, say N. The program then prints the sum of the first N natural numbers. Figure 4.4 is a sample output of running the revised program.

CalculateScanner.JPG

Figure 4.4: Calculating the first N natural numbers

4.4.1.  (10 pts) Program Design: Write a pseudocode Draw a UML activity diagram to show the algorithm of the revised program.

4.4.2.  (10 pts) Program Implementation: Attached the revised Java program.

4.4.3.  (15 pts) Program verification: Test the program to ensure it meets the requirements. Give the TA a demo of your working program.

 

4.5.   Static versus Instance Methods

4.5.1.    (15 pts) Rewrite the Calculate program from above by moving the statements of calculating the sum of the first N natural numbers into a static method called calculateSum( ). As shown below, the method takes an integer upper, which represents a natural number, calculates the sum of 1 + 2 + … + upper, and returns the sum as a long value to the calling method. Attach the revised program.

long calculateSum (int upper)

4.5.2.    (15 pts) Repeat the exercise above, but this time define an instance method called calculateTotal( ), which performs the same calculation as calculateSum( ). Note: An instance method can only be “invoked” via an object. Attach the revised program.

4.5.3.  (15 pts) Verification: Test the program to ensure both methods work correctly. Give the TA a demo of your working program.

 

Go to the Index


  • Lab 5

Total points=100

5.1.   This exercise focuses on the creation of serializable objects that can be saved into and retrieved from a binary file, using ObjectInputStream and ObjectOutputStream.

5.1.1.    (5 pts) The Person class as shown in Figure 3.1 can be downloaded from this link. Make necessary revisions to make the Person class serializable.

5.1.2.    (10 pts) Revise the CreateSequentialFile.java program (Figure 17.16 in the book) and the CreateSequentialFileTest.java program (Figure 17.17 in the book) to make them capable of handling the Person class. As shown in Figure 1, the revised program should take first name, last name, and age for each of the persons until the user enter <ctrl> z to end the input. The user input will be saved into the file persons.ser.

5.1.3.    (10 pts) Run the CreateSequentialFileTest application using JDK to create the persons.ser file. Give the TA a demo of your working program.

 

5.1.4.    (10 pts) Revise the ReadSequentialFile.java program (Figure 17.18 in the book) and the ReadSequentialFileTest.java program (Figure 17.19 in the book) to make them capable of handling the Person class. As shown in Figure 2, the revised program should read data stored in the file persons.ser and deserialize the objects.

5.1.5.    (10 pts) Run the ReadSequentialFileTest application using NetBeans. (Note: You may need to revise the Working Directory to make it work.) Give the TA a demo of your working program.

Figure 5.1: Creating the persons.ser file to store the Person objects

 

Figure 5.2: Reading data from the persons.ser file to restore the Person objects

 

5.2.  Based on Exercise 7.17 from the text book:

5.3.   (5 pts) As shown in the table above, the probability of having the sum of the two dice as 2 is 1/36 (or about 2.8%). What is the probability for each of the other possible sums (like 3, 4, 5, 6, 7, 8, 9, 10, 11, and 12)? Show how you get your answers.

5.4.    Develop an application for the problem discussed in Exercise 7.17.

5.4.1.    (10 pts) Architectural Design: Draw a UML class diagram (with associations, if necessary) to show your design of the application.

5.4.2.    (10 pts) Algorithm Design: Use a pseudocode, flowchart, or activity diagram to show the detailed algorithm of your solution.

5.4.3.    (20 pts) Implementation: Develop the Java application using either JDK or NetBeans. As noted in the exercise description, your application needs to roll the dice 36,000,000 times. When tallying the result, in addition to tallying the number of times each possible sum appears, also show the percentage of occurrence for each possible sum.

5.4.4.    (10 pts) Verification: Give the TA a demo of your working program.

 

Go to the Index


  • Lab 6

Total points=100

This project is based on the object-oriented design exercise discussed in class when Chapter 9 (Inheritance) was covered.

A.    Project description:

Design a Java application with the following classes: Person, Employee, Customer, CommissionEmployee, and BasePlusCommissionEmployee.

Place the following attributes into the appropriate classes: salutation, first name, middle name, last name, social security number, account id, phone number, address, base salary, commission rate, sales, salary, position title, etc. You may add additional attributes, but ensure to have these required attributes included first.

 

B.     (30 pts) Object-Oriented design:

1)     Draw the inheritance hierarchy to show the superclass/subclass relationship between the classes.

2)     Draw a detailed UML class diagram (with associations) to show your design of the application.

 

C.    (40 pts) Implementation:

Convert the object-oriented design into Java programs.

Specific implementation requirements include the following:

1)     Place all five classes into a package called businessCompany.

2)     Develop a driver program called businessCompanyTest to test the developed classes. In the driver program, create five instances of Customer, three instances of CommissionEmployee and three instances of BasePlusCommissionEmployee.

3)     In the driver program, save the created objects into respective files. That is, the objects of Customer will be saved in a file called Customer.dat, and the objects of CommissionEmployee will be saved in a file called CommissionEmployee.dat, and so on.

4)     In the driver program, develop a static method to read the three files and display their content on the screen.

5)     Your class definitions should exhibit good object-oriented programming practice, especially those discussed in Chapters 8 and 9, such as data hiding using set and get methods, proper access modifiers, etc.

 

D.    (30 pts) Verification:

Ensure all the requirements are met in your application. Give the TA a demo of your application. You may choose to use either JDK or NetBeans for the demonstration.

 

Go to the Index


  • Bonus Lab (optional)

Note: Students who have successfully completed this bonus project will earn up to an additional 4% of the total grade.

Total points=100

a)     Project description:

As discussed in class, there exist four different access modifiers for instance variables and methods in a Java class. The purpose of this lab is to test and verify the various access modifiers.

A sample Java application: As illustrated in Figure B, the classes Alpha and Beta belong to Package One, while classes AlphaSub and Gamma are part of Package Two. Class AlphaSub is a subclass of class Alpha.

 

Figure B. An illustration of Java’s access modifiers

(source: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)

 

Objectives: Design and implement a Java application that tests the visibility of the members of the Alpha class as shown in the table in Figure B.

Note: The application AccessModifiersAndPackages.htm (available from http://sce.uhcl.edu/yang/teaching/JavaProgrammingExamplesandRelatedTopics.htm) illustrates how to test the visibility of instance variables. You may build your application based on that sample application.

 

b)     (30 pts) Object-Oriented Design:

Draw a UML class diagram to show the name, attributes and methods of each of the classes in your application. Include appropriate associations between the classes. Hand in the class diagram.

 

c)      (40 pts) Implementation:

Implement your design by converting them into Java classes. Your class definitions should exhibit good object-oriented programming practice, especially those discussed in Chapters 8 and 9, such as data hiding using set and get methods, proper access modifiers, etc. Hand in the source programs.

 

d)     (30 pts) Verification:

Give the TA a demo of your working program. You may choose to use either JDK or NetBeans for the demonstration.

Important: Ensure that all the 16 cases are tested in your application. For each of the 16 cases, print an appropriate message like “Protected instance variable iv1 in Alpha is visible in Beta” or “Private instance variable iv2 in Alpha is not visible in AlphaSub”.

 

Go to the Index