Solution

advertisement
Examples
1. EmployeeSortTest.java
/**@version 1.20 07 Apr 1998
* @author Cay Horstmann
*/
import java.util.*;
import corejava.*;
public class EmployeeSortTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 35000, new Day(1989,10,1));
staff[1] = new Employee("Carl Cracker", 75000, new Day(1987,12,15));
staff[2] = new Employee("Tony Tester", 38000, new Day(1990,3,15));
ArrayAlg.shellSort(staff);
int i;
for (i = 0; i < staff.length; i++)
System.out.println(staff[i]);
}
}
abstract class Sortable
{
public abstract int compareTo(Sortable b);
}
class ArrayAlg
{
public static void shellSort(Sortable[] a)
{
int n = a.length;
int incr = n / 2;
while (incr >= 1)
{
for (int i = incr; i < n; i++)
{
Sortable temp = a[i];
int j = i;
while (j >= incr && temp.compareTo(a[j - incr]) < 0)
{
a[j] = a[j - incr];
j -= incr;
}
a[j] = temp;
}
incr /= 2;
}
}
}
class Employee extends Sortable
{
private String name;
private double salary;
private Day hireDate;
public Employee(String n, double s, Day d)
{
name = n;
salary = s;
hireDate = d;
}
public void raiseSalary(double byPercent)
{
salary *= 1 + byPercent / 100;
}
public String getName() { return name; }
public double getSalary() { return salary; }
public String toString()
{
return name + " " + salary + " " + hireYear();
}
public int hireYear()
{
return hireDate.getYear();
}
public int compareTo(Sortable b)
{
Employee eb = (Employee)b;
if (salary < eb.salary) return -1;
if (salary > eb.salary) return 1;
return 0;
}
}
2. TileTest.java
/**
* @version 1.20 07 Apr 1998
* @author Cay Horstmann
*/
import java.awt.*;
import java.util.*;
public class TileTest
{
public static void main(String[] args)
{
Tile[] a = new Tile[20];
int i;
for (i = 0; i < a.length; i++)
a[i] = new Tile(i, i, 10, 20, (int)(100 * Math.random()));
Arrays.sort(a);
for (i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
class Tile extends Rectangle implements Comparable
{
private int z;
public Tile(int x, int y, int w, int h, int zz)
{
super(x, y, w, h);
z = zz;
}
public int compareTo(Object b)
{
Tile tb = (Tile)b;
return z - tb.z;
}
public String toString()
{
return super.toString() + "[z=" + z + "]";
}
}
3. TestReflection.java
import java.lang.reflect.*;
public class TestReflection
{
public static void main(String[] args)
{
reflectionClass rc = new reflectionClass();
System.out.println(rc.toString());
}
}
class reflectionClass
{
public int field1 = 10;
public String field2 = "It is me.";
public String toString()
{
java.util.Hashtable h = new java.util.Hashtable();
Class cls = getClass();
Field[] f = cls.getDeclaredFields();
try
{
AccessibleObject.setAccessible(f, true);
for (int i = 0; i < f.length; i++)
h.put(f[i].getName(), f[i].get(this));
}
catch (SecurityException e) {}
catch (IllegalAccessException e) {}
if (cls.getSuperclass().getSuperclass() != null)
h.put("super", super.toString());
return cls.getName() + h;
}
}
4. ListOfNumbers.java
/*The writeList method calls two methods that can throw exceptions:
(1). The following line invokes the constructor for FileWriter, which throws an
IOException if the file cannot be opened for any reason:
out = new PrintWriter (new FileWriter("OutFile.txt"));
(2) The Vector class's elementAt method throws an ArrayIndexOutOfBoundsException if
you pass in an index whose value is too small (a negative number) or too large (larger
than the number of elements currently contained by the Vector).
out.println("Value at: " + i + " = " + victor.elementAt(i));
*/
import java.io.*;
import java.util.Vector;
public class ListOfNumbers
{
private Vector victor;
private static final int size = 10;
public ListOfNumbers ()
{
victor = new Vector(size);
for (int i = 0; i < size; i++) victor.addElement(new Integer(i));
}
public void writeList()
{
PrintWriter out = new PrintWriter (new FileWriter("OutFile.txt"));
for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));
out.close();
}
}
Solution
Interface and Packages
Question 1: What methods would a class that implements the java.util.Iterator interface
have to implement?
Answer 1: next, hasNext, and remove
Question 2: What is wrong with the following interface?
public interface SomethingIsWrong
{
public void aMethod(int aValue)
{
System.out.println("Hi Mom");
}
}
Answer 2: It has a method implementation in it. It should just have a declaration.
Question 3: Fix the interface in Question 2.
Answer 3:
public interface SomethingIsWrong
{
public void aMethod(int aValue);
}
Question 4: Is the following interface valid?
public interface Marker
{}
Answer 4: Yes. Methods are not required. Empty interfaces can be used as types and to
mark classes without requiring any particular method implementations. For an example
of a useful empty interface, see java.io.Serializable.
Exception Handling
Question 1. List five keywords that are used for exception-handling.
Answer: try, throw, catch, finally, and throws
Question 2.All exceptions in Java are thrown by code that you write: True or False? If
false, explain why.
Answer: False. There are situations where an exceptional condition automatically
transfers control to special exception-handling code which you write (cases where you
don't provide the code to throw the exception object).
Question 3.Explain why you should place exception handlers furthermost from the root
of the exception hierarchy tree first in the list of exception handlers
Answer: An exception handler designed to handle a specialized "leaf" object may be
preempted by another handler whose exception object type is closer to the root of the
exception hierarchy tree if the second exception handler appears earlier in the list of
exception handlers
Question 4.Provide a code fragment that illustrates how you would specify that a method
throws more than one exception
Answer:
void myMethod() throws InterruptedException, MyException,
HerException, UrException
{
//method body
}
1. IteratorDemo.java
public class IteratorDemo implements java.util.Iterator
{
private String[] cardNames = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack",
"Queen", "King", "Ace"};
private int current = 0;
public boolean hasNext()
{
if (current == cardNames.length) return false;
else return true;
}
public Object next()
{
return (Object)cardNames[current++];
}
public void remove()
{
throw new UnsupportedOperationException();
}
public static void main(String[] args)
{
IteratorDemo i = new IteratorDemo();
while (i.hasNext())
{
System.out.println(i.next());
}
}
}
2. TimeClient .java
public interface TimeClient
{
public void setTime(int hour, int minute, int second);
public void setDate(int day, int month, int year);
public void setDateAndTime(int day, int month, int year, int hour, int minute,
int second);
}
3. ExcpHandle.java
class ExcpHandle
{
public static void main(String[] args)
{
try
{
for(int cnt = 2; cnt >-1; cnt--)
{
System.out.println("Program is running. The quotient is: "
+ 6/cnt);
}
}
catch(ArithmeticException e)
{
//put corrective code in here
System.out.println("\nOops, caught an exception with the message:"
+ e.getMessage() + "\nand with the stacktrace showing:");
e.printStackTrace();
System.out.println("Converting the exception object to a String”
+ “ we get:\n" + e.toString());
System.out.println("In a real program, we might take corrective”
+ “ action here");
}
}
}
Download