Spring 2002, CSE 428: Assignment 4


Distributed: Feb 22.
Due: Mar 21 in class.
Total maximum score: 100 points.

The purpose of this assignment is to provide experience with Exception Handling and Concurrent Programming in Java


Exercise 1 [Points 50]

The following Java program should allow the user to compute sums of integers given in input. The program repeatedly asks the user if he/she wants to calculate a sum; if the answer is yes, then the program takes in input a sequence of integers terminated by a 0, then prints its sum, and asks the same quetion again. If the answer is no, then the program terminates.

import java.io.*;

public class Sums {

    public static void sum(BufferedReader in){ 
        // takes a sequence of integeres in input, and outputs their sum

	int s, nextInt;
	s = 0;

	System.out.println("Please input the sequence of integers to sum, terminated by a 0");
        nextInt = Integer.parseInt(in.readLine());
                //Read next datum in input. An integer is expected

	while (nextInt!=0) {
	    s = s + nextInt;
	    nextInt = Integer.parseInt(in.readLine());
	}

        System.out.println("The sum is " + s);
    }

    public static void main(String[] arg) {         

	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                         //"in" will receive data from the standard input stream
	String c;
 
	System.out.println("Do you wish to calculate a sum? (y/n)");

	c = in.readLine();
         //Read next datum in input. A string "y" or "n" is expected

	while (!c.equals("y") && !c.equals("n")) {
	    System.out.println("Please answer y or n");
	    c = in.readLine();
	}

	while (c.equals("y")) {
	    sum(in);
	    System.out.println("Do you wish to calculate another sum? (y/n)");
	    c = in.readLine();

	    while (!c.equals("y") && !c.equals("n")) {
		System.out.println("Please answer y or n");
		c = in.readLine();
	    }
	}

	System.out.println("Goodbye");
    }
}

The program as it is written, however, will not even pass compilation, because of uncaught (checked) exceptions.

Please modify the program and add the suitable try-catch statement(s) so to cope with the following exceptions:

  1. NumberFormatException: an exception of this kind means that the datum returned by in.readLine() does not represent an integer. If this occurs, the user should be asked to reenter the datum and continue.
  2. IOException: an exception of this kind means that the readLine() operation could not be completed normally, for instance because of a coding error. Also in this case, the user should be asked to reenter the datum and continue.

Example of session:

java Sums

Do you wish to calculate a sum? (y/n)
y
Please input the sequence of integers to sum, terminated by a 0
20              
5
a
Invalid number. Please reenter.
2
0
The sum is 27
Do you wish to calculate another sum? (y/n)
s
Please input y or n
y
Please input the sequence of integers to sum, terminated by a 0
870
30
0
The sum is 900
Do you wish to calculate another sum? (y/n)
y    
Please input the sequence of integers to sum, terminated by a 0
0
The sum is 0
Do you wish to calculate another sum? (y/n)
n
Goodbye


Exercise 2 [Points 50]

Consider the program PingPong of Lecture Notes 13:
public class PingPong extends Thread {
    private String word;  // what word to print
    private int delay;    // how long to pause (in milliseconds)
  
    public PingPong(String whatToSay, int delayTime) {
        word = whatToSay;
        delay = delayTime;
    }

    public void run() {
        try {
            for (;;) {
                System.out.print(word + " ");
                sleep(delay);   // pause before printing next word
            }
        } catch (InterruptedException e) {
            return;   // end this thread
        }
    }

    public static void main(String[] args) {
        new PingPong("ping",  33).start();  // 1/30 second
        new PingPong("PONG", 100).start();  // 1/10 second
    }
}
Modify the program in such a way that the user is requested to give in input
  1. The number of threads
  2. For each thread, the word to print and the number of milliseconds to sleep between two consecutive prints.
Example of session (assuming that the new program is called PrintWords):
java PrintWords

please input the number of threads
3
please input the word of thread 1
din
please input the delay of thread 1
33
please input the word of thread 2
don
please input the delay of thread 2
33
please input the word of thread 3
dan
please input the delay of thread 3
33

din don dan din don dan din don dan din don 
dan din don dan din don dan din don dan din
don dan din don dan din don dan din don dan
...
The program should be robust wrt NumberFormatException and IOException. These exceptions should be treated like in previous exercise.

Note: The order in which the threads are activated may be different from the above one. For instance, you could get don din dan don din dan ... instead. Also, the order may change (for instance, you could get don din dan dan don din ... ). This is normal, because the scheduling policy is unpredictable and in general differ from machine to machine.

Please note the following:.

  1. Please make sure that your programs can be compiled with the Unix javac and executed with the Unix java. Programs which cannot be compiled or executed will receive, at most, 20 points.
  2. Please call the classes of your programs Sums and PrintWords respectively, and save them in two files named Sums.java and PrintWords.java respectively. Make sure that the programs can be compiled and executed with the following commands:
           javac Sums.java
           java Sums
           
    and
           javac PrintWords.java
           java PrintWords
           
  3. Its your responsibility to write sound, reliable programs, so please test your code thoroughly before submitting it.

Format of the solution

Please give an hard copy of the source programs to the instructor by the due date. Furthermore, you should also email your sources to cg428@cse.psu.edu by the due date, so to allow us to check that they run correctly. Please send the two files Sums.java and PrintWords.java as two attachments, not by "cut-and-paste". Please write in the subject of the email your section, your name, and your student id.