Difference between revisions of "CSC212 Lab 5 2014"
(→Problem 1: Generic Classes) |
|||
Line 69: | Line 69: | ||
::* U. Padua, 1222 | ::* U. Padua, 1222 | ||
::* U. Naples, 1224 | ::* U. Naples, 1224 | ||
− | : Make your program output the 6 pairs. | + | : Make your program output the 6 pairs. <font color="magenta"> Verify that your program works.</font> |
<br /> | <br /> | ||
Revision as of 05:56, 24 September 2014
--D. Thiebaut (talk) 16:12, 23 September 2014 (EDT)
Problem 1: Generic Classes
- Store the program below in a file called Pair.java
public class Pair<T, P> { private T first; private P second; public Pair( T f, P s ) { first = f; second = s; } public T getFirst() { return first; } public P getSecond() { return second; } public void setFirst( T f ) { first = f; } public void setSecond( P s ) { second = s; } public String toString( ) { return "(" + first + ", " + second + ")"; } }
- Store the program below in a file called TestPair.java
class TestPair { static public void main( String[] args ) { Pair<Integer, Integer> p1 = null, p2 = null; p1 = new Pair<Integer, Integer>( 10, 3 ); p2 = new Pair<Integer, Integer>( 5, -9 ); System.out.println( "p1 = " + p1 ); System.out.println( "p2 = " + p2 ); p1.setFirst( p2.getSecond() ); System.out.println( "p1 = " + p1 ); } }
- Question 1
- Compile and run your program:
javac TestPair.java Pair.java java TestPair
- Verify that your program works.
- Question 2
- Modify the toString() method of Pair.java, so that it prints a pair this way: [10|3]', rather than (10, 3). Verify that your edited program works.
- Question 3
- Change TestPair.java and replace Integer with Double, so that your program can hold pairs of real numbers. Update the initialization of p1 and p2, so that you store real numbers in the pairs (e.g. 3.14159). Verify that your edited program works. Notice that you do not have to modify Pair.java at all; that's the beauty of a generic class: it will work for any type of data you want it to contain.
- Question 4
- Change TestPair.java again, and this time modify it so that p1 and p2 will contain ( "Smith College", 1871 ), and ( "Amherst College", 1821). Verify that your edited program works.
- Question 5
- Study the solution program for Exercise 2 (seen in class). Modify TestPair.java so that it now holds an array of 6 (String, Integer) pairs. Initialize the array with these university names and the year they were founded:
- U. Bologna, 1088
- U. Oxford, 1167
- U. Cambridge, 1209
- U. Salamanca, 1218
- U. Padua, 1222
- U. Naples, 1224
- Make your program output the 6 pairs. Verify that your program works.
Problem #2
- create a generic class for triplet
- create array of 10 triplets( )
- exception:
- secure some pieces of code with try catch
- throw