PIC 20A Lecture 1, Spring 2001

Instructor: Fedor A. Andrianov

MIDTERM EXAM



STUDENT DATA:




1. (20 points):
Fill in the blanks in each of the following:


2. (20 points):
The following program contains several bugs. Please find and fix them.
    public class SomethingIsWrong {
	public interface anInterface {
	    void aMethod(int aValue) { System.out.println("Hi Mom"); }
	}
	public static void main(String[] args) {
	    StringBuffer[] stringBuffers = new StringBuffer[10];
	    for (int i = 0; i < stringBuffers.length; i++) {
		stringBuffers[i].append("String Buffer at index " + i);
	    }
	}
    }
Please write your answer on the other side of page 1 --->
    public class SomethingIsWrong {
	public interface anInterface {
	    //interface should not implement any methods
	    void aMethod(int aValue);
	}
	public static void main(String[] args) {
	    StringBuffer[] stringBuffers = new StringBuffer[10];
	    for (int i = 0; i < stringBuffers.length; i++) {
		//array elements should be created before they can be used
		stringBuffers[i] = new StringBuffer();
		stringBuffers[i].append("String Buffer at index " + i);
	    }
	}
    }


3. (20 points):
Answer the following questions:
Answers:


4. (20 points):
Suppose that you have written a time server, which periodically notifies its clients of the current date and time. Write an interface that the server could use to enforce a particular protocol on its clients. Please write your answer on the other side of page 2 --->
    public interface TimeWatcher {
	public void setTime(int h, int m, int s);
	public void setDate(int mo, int d, int y);
    }


5. (20 points):
Create a program that reads an unspecified number of integer arguments from the command line and adds them together. For example, suppose that you enter the following:
    java Adder 1 3 2 10 
The program should display 16 and exit. In addition, your program should catch and handle all exceptions that might arise because of a bad input. Each type of exception should be handled independently, by printing an appropriate error message which would specify what exactly was wrong with the input. Hint: to convert a string representing an integral number into an integer, you can use method
    public static int java.lang.Integer.parseInt(String s)
	    throws NumberFormatException 


    public class Adder {
	public static void main(String[] args) {

	    try {
		int sum = Integer.parseInt(args[0]);
		for (int i = 1; i < args.length; i++) {
		    sum += Integer.parseInt(args[i]);
		}
		System.out.println("The sum is " + sum);

	    } catch (NumberFormatException ex) {
		System.out.println("Please enter only integral arguments.");

	    } catch (ArrayIndexOutOfBoundsException ex) {
		System.out.println("Please enter one or more integral arguments.");
	    }
	}
    }


Good Luck !

Last modified on by fedandr@math.ucla.edu.