Difference between revisions of "CSC212 Lab 5 2014"

From dftwiki3
Jump to: navigation, search
(Problem #3: Exceptions)
(Problem #3: Exceptions)
Line 89: Line 89:
 
<br />
 
<br />
  
=Problem #3: Exceptions=
+
=Problem #3: Review '''Continue''' and '''Break''' Statements=
 +
<br />
 +
* This tiny section is just to make sure you remember how '''break''' and '''continue''' work in loops.  They work equally well in '''for-loops''' as in '''while-loops'''.
 +
* Study the program below.
 +
* Guess its output.
 +
* <font color="magenta">Run the program and verify that intuition was correct!</font>
 +
<br />
 +
:::<source lang="java">
 +
public class ContinueBreak {
 +
 
 +
public static void main(String[] args) {
 +
 
 +
for ( int i=0; i<100; i++ ) {
 +
if ( i % 3 == 0 )
 +
continue;
 +
if ( i >= 50 )
 +
break;
 +
System.out.println( "i = " + i);
 +
}
 +
}
 +
 
 +
}
 +
 
 +
</source>
 +
<br />
 +
=Problem #4: Exceptions=
 
[[Image:Bomb.jpg|right|250px|http://4.bp.blogspot.com/-UfVU-B94K0A/UFH6jxMoy9I/AAAAAAAAFt4/qzZuyn5_-kE/s1600/bomb.jpeg]]
 
[[Image:Bomb.jpg|right|250px|http://4.bp.blogspot.com/-UfVU-B94K0A/UFH6jxMoy9I/AAAAAAAAFt4/qzZuyn5_-kE/s1600/bomb.jpeg]]
 
<br />
 
<br />
 +
==Simple Exceptions==
 
* Create a new program called Bomb.java with the following code:
 
* Create a new program called Bomb.java with the following code:
 
<br />
 
<br />
Line 126: Line 152:
 
System.out.println( "Please enter 2 integers (-1 to stop): ");
 
System.out.println( "Please enter 2 integers (-1 to stop): ");
 
int n1 = input.nextInt();
 
int n1 = input.nextInt();
                         if ( n1==-1 )  
+
int n2 = input.nextInt();
 +
                         if ( n1==-1 || n2==-1 )  
 
                               break;
 
                               break;
int n2 = input.nextInt();
 
 
try {
 
try {
 
System.out.println( n1 + " / " + n2 + " is " + (n1/n2) );
 
System.out.println( n1 + " / " + n2 + " is " + (n1/n2) );
Line 139: Line 165:
 
</source>
 
</source>
 
<br />
 
<br />
 +
 +
;Question 1
 +
: There are also other potential traps in your program: try inputting a string instead of an integer, for example.  Note the exception, and its name.

Revision as of 07:37, 24 September 2014

--D. Thiebaut (talk) 16:12, 23 September 2014 (EDT)


Problem 1: Generic Classes

from research.microsoft.com/en-us/um/people/akenn/generics/cupt.jpg


  • 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 ( "Hampshire College", 1965). 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 your Own Generic Class


  • Create a new generic class that will hold a triplet (i.e. 3 items). Call it Triplet.java and use Pair.java as an example.
  • Create a new class called TestTriplet.java that you will adapt from TestPair.java. Make your TestTriplet.java use 3-integer triplets. Verify that your edited program works.



Question 1
Modify TestTriplet.java so that it now holds two ( String, Double, Integer) triplets: p1, and p2. Verify that your edited program works.


Question 2
Modify TestTriplet.java so that now it holds ( String, Integer, Pair( Integer, Integer ) ) !!!
You shouldn't have to modify Triplet.java at all! Initialize p1 to ( "Smith College", 1871, ( 2600, 2014 ) ), and p2 to ( "Hampshire College", 1965, ( 1400, 2014 ) ). Verify that your edited program works.


Question 3
Modify TestTriplet.java and make it hold an array of 5 (Integer, Integer, Integer) triplets. Initialize the triplets as you wish. Verify that your edited program works.


Problem #3: Review Continue and Break Statements


  • This tiny section is just to make sure you remember how break and continue work in loops. They work equally well in for-loops as in while-loops.
  • Study the program below.
  • Guess its output.
  • Run the program and verify that intuition was correct!


public class ContinueBreak {

	public static void main(String[] args) {

		for ( int i=0; i<100; i++ ) {
			if ( i % 3 == 0 )
				continue;
			if ( i >= 50 )
				break;
			System.out.println( "i = " + i);
		}
	}

}


Problem #4: Exceptions

http://4.bp.blogspot.com/-UfVU-B94K0A/UFH6jxMoy9I/AAAAAAAAFt4/qzZuyn5_-kE/s1600/bomb.jpeg


Simple Exceptions

  • Create a new program called Bomb.java with the following code:


import java.util.Scanner;

public class Bomb {
	
	public static void main(String[] args) {
		Scanner input = new Scanner( System.in );
		
		while ( true ) {
			System.out.println( "Please enter 2 integers"
                                                    +" (-1 to stop): ");
			int n1 = input.nextInt();
                        if ( n1==-1 ) 
                              break;
			int n2 = input.nextInt();
			System.out.println( n1 + " / " + n2 + " is " + (n1/n2) );
		}

	}

}


  • Run your program and enter some numbers. Nothing terribly exciting will happen, until you enter 0 as the second number, of course. Try it.
  • Boom!
  • Note the name of the exception that appears on your screen: java.lang.SomeNameException.
  • Edit your program so that you can now catch the exception and process it. Put the try/catch statement as close to the problematic code as possible (and replace xxxxxxxxxxxxxxx by the actual exception name).
	
		while ( true ) {
			System.out.println( "Please enter 2 integers (-1 to stop): ");
			int n1 = input.nextInt();
			int n2 = input.nextInt();
                        if ( n1==-1 || n2==-1 ) 
                              break;
			try {
				System.out.println( n1 + " / " + n2 + " is " + (n1/n2) );
			}
			catch (  xxxxxxxxxxxxxxx  e ) {
				System.out.println("Exception: " + e.getMessage() + 
									"\nReenter numbers." );
			}
		}


Question 1
There are also other potential traps in your program: try inputting a string instead of an integer, for example. Note the exception, and its name.