Download - CS 180 Final Exam Review 12/(11, 12)/08
Announcements
Final Exam Thursday, 18th December, 10:20 am – 12:20 pm in
PHYS 112 Format
30 multiple choice questions 5 programming questions
More stress on topics (chap 11 – 15) covered after exam 2 Recursion Dynamic Data Structures Window Interfaces using Swing Applets and HTML More Swing
Object-Oriented Design
Methods Extract functionalities of a program which will
be performed multiple times Encapsulation and Information Hiding Classes, Objects, and Polymorphism
Covered in more detail later
Primitives
int, double, boolean, float, char, etc.
These are NOT Objects Can be compared with ==, !=, <=, >=, etc. Wrapper classes for each primitive
Why do we need them?
Explicit type-casting may need to be done byteshortintlongfloatdouble
Objects and Classes Class variables hold references (the address) to the objects Always compare with the equals() method
Do NOT use == to compare objects Assignment operators assign references – they do not make
separate copies Constructors should be used to initialize class variables
Calling methods Need object Static methods
Can use class name Cannot access non-static methods/variables inside
Pass by value always
Keyword: this
Strings Strings are a type of object
Also should not be compared with ==
Important String functions charAt indexOf substring length Concatenation operator +
Selection Statements Modifies the flow of control of the program if/else construct
Must have a boolean condition to check against { } are strongly recommended, but not necessary for
one line statements switch construct
Multi-way branch which makes a decision based on a char, byte, short, or int type
default case break statement
Repetition statements - Loops
for while do-while Beware of -
Off-by-one errors Infinite looping Overflow
Arrays Linear collection of data
Can hold primitives or class types, but must all be of the same type
length tells the number of elements in the array Member, not a method
Indexed from 0 to length – 1 Multiple dimension arrays Convenient to use for-loops to iterate through
members of the array Remember – arrays are reference types
Exceptions
Use a try/catch/finally block to handle exceptions thrown by a program
Use throw statement to notify caller of an error
User defined exceptions must extend Exception
File I/O
Useful classes FileInputStream, DataInputStream, FileReader,
BufferedReader, Scanner, PrintWriter, DataOutputStream, etc.
ObjectInputStream, ObjectOutputStream Used to write objects to a file Any object serialized by a stream must implement
Serializable Which classes are used to write text and which
are used to write binary? Always close files you open
Inheritance and Polymorphism Differences between abstract classes and
interfaces Polymorphism can simplify code Extend specific classes from general classes Use protected keyword to protect information
and methods Reuse inherited functionality from parent class. Call to base class’s constructor is always called
at the first line of constructor.
Dynamic Data Structures
Inner classes Lists
Node class Circularly linked lists Doubly linked lists
Trie data structure ( from project 7 ) Java Collections
Vector ArrayList LinkedList
Recursion
Break down a problem to one or more sub-problems
Be concerned only with the current level of recursion
Two necessary cases Base case Recursive step
GUI and Event-driven Programming
Common classes JFrame JPanel JLabel JMenu, JMenuItem JButton
Layouts BorderLaout GridLayout FlowLayout
Types Given the following classes, which of the following
declarations are valid?public interface I {…}
public interface J extends I {…}
public interface K {…}
public abstract class A {…}
public class B extends A {…} implements J, K
public class C extends B {…}
public class D extends A {…} implements I
A a = new B();B b = new J();C c = new B();B b = new C();I i = new A();I i = new B();I i = new D();K k = new C();
Types Given the following classes, which of the following
declarations are valid?public interface I {…}
public interface J extends I {…}
public interface K {…}
public abstract class A {…}
public class B extends A {…} implements J, K
public class C extends B {…}
public class D extends A {…} implements I
A a = new B();B b = new J();C c = new B();B b = new C();I i = new A();I i = new B();I i = new D();K k = new C();
valid – B is a subclass of Ainvalid – cannot instantiate interfacesinvalid – B is the superclass of Cvalid – C is a subclass of Binvalid – A does not implement Ivalid – A implements J, and J is-a Ivalid – D implements Ivalid – C extends B which implements K
Recursion and Linked Lists
Question-A gradebook is made out of the the following Node class.
class Node{
private int[] values; // these values are sorted in ascending orderprivate Node next;
public Node(int[] values, Node next)public int[] getValues()public void setValues(int[] values)public Node getNext()public void setNext(Node next)
}1)Each Node contains an array of scores that are within a certain range. 2)The gradebook contains a linked list of the Node class.For example, you may use the 1st Node to store all the scores in the F range, the 2nd Node to store all the scores in the D range, the 3rd Node to store all the scores in the C range, etc.
Recursion and Linked Lists
Question continued-
Each node represents a non-overlapping group of grade values and each successive Node contains a range of group values greater than the previous Node.
Write an efficient method gradeExists(int), which returns true if the grade exists within the Gradebook, and false otherwise.
Since the values array is sorted, you should take advantage of this and perform a binary search for the specified value.
Recursion and Linked Lists
Approach to the solution:
The solution can be broken into two parts:1.Finding the node which might contain the grade. Since all nodes have non-overlapping ranges (in sorted order) and the arrays in turn are sorted, we only need to compare the range of each node with the given grade.
2.Do binary search on the values in that node.
Recursion and Linked Lists
Part 1: public boolean gradeExists(int grade) {
Node temp = gradebook;while (temp != null){
int[] values = temp.getValues();if (grade < values[0])
return false;if (grade >= values[0] && grade <=
values[values.length-1])return binarySearch(values, grade, 0,
values.length-1); temp = temp.getNext();
}return false;
}
Recursion and Linked Lists
Part 2:private boolean binarySearch(int[] array, int value, int lo, int hi){
if (lo > hi)return false;
if (lo == hi)return array[lo] == value;
int mid = (hi + lo)/2;if (array[mid] == value)
return true;else if (array[mid] > value)
return binarySearch(array, value, lo, mid-1);else
return binarySearch(array, value, mid+1, hi);}
Recursion
Write a function isPalindrome(String) which takes in a String and returns true if the String is a palindrome, false otherwise.Ignore the case of the letters and skip over blanks when you make the comparison.public boolean isPalindrome(String s){
}
Recursion
Solution:public boolean isPalindrome(String s){
if (s == null)return false;
if (s.length() <= 1)return true;
return ( s.charAt(0) == s.charAt(s.length()-1) &&isPalindrome(s.substring(1, s.length()-
1)) );}public static void main(String[] args){
...result = isPalindrome(s.toLowerCase().replace(“ “,””));
}
GUI
Question:Create a complete Java GUI program that allows the user to enter the text for JLabels, possibly with multiple lines, and then preview them. You should use the following design:
The user can enter text in the text area. Then, when the button is pushed, this text is displayed as a label in the label preview.
Title
Button
Text Area Label Preview
Enter Text: Label Preview:
GUI - solution
public class CH12 extends JFrame implements ActionListener
{ JButton theButton = new JButton(
"Preview" ); JTextArea theText = new JTextArea(); JLabel theLabel = new JLabel();
public CH12() {super( "Label Previewing Program" );setSize( 400, 200 );
//button in south JPanel aPanel = new JPanel();aPanel.add( theButton );this.add( "South", aPanel ); //label in northaPanel = new JPanel();aPanel.add( new JLabel("The Label
Previewer") );this.add( "North", aPanel );
JPanel centerPanel = new JPanel( new GridLayout(1,2) ); //text area in center leftaPanel = new JPanel( new BorderLayout());aPanel.add( "North", new JLabel("Enter
Text:") );theText.setLineWrap( true );aPanel.add( "Center", theText );centerPanel.add( aPanel ); //preview label in center rightaPanel = new JPanel( new BorderLayout());aPanel.add( "North", new JLabel("Label
Preview:") );aPanel.add( "Center", theLabel );centerPanel.add( aPanel ); this.add( "Center", centerPanel ); theButton.addActionListener( this ); }
GUI – solution contd. public void actionPerformed( ActionEvent e )
{ theLabel.setText( theText.getText() ); }
public static void main( String[] args ) { JFrame ch12Frame = new CH12(); ch12Frame.setVisible( true ); }
} //end of class def
Arrays
Write a method which takes in an array of integers and replaces the values of the array with a value ci, where ci is defined as –ci = the sum of the numbers in indices 0…i in the incoming array.
public void cumulativeArray(int[] a) {
}
Arrays Write a method which takes in an array of integers and
replaces the values of the array with a value ci, where ci is defined as –ci = the sum of the numbers in indices 0…i in the incoming array.
public void cumulativeArray(int[] a) {if (a.length <= 1)
return;for (int k=1; k<a.length; k++)
a[k] = a[k] + a[k-1];}
What is the output?public class A{
private int x;
public static int doStuff(){
x = 100;x /= 3;x++;return x;
}
public static void main(String[] args){
System.out.println(A.doStuff());}
}
What is the output?
public class A{
private int x;
public static int doStuff(){
x = 100;x /= 3;x++;return x;
}
public static void main(String[] args){
System.out.println(A.doStuff());}
}
Because this method is static, it does not haveaccess to non-static class variables. This code will not compile because x is non-static.
Linked Lists Given an appropriate Node class, write a method
which removes every other node from the list, starting with the second.
public Node removeEveryOther(Node l){
}
Linked Lists Given an appropriate Node class, write a method
which removes every other node from the list, starting with the second.
public Node removeEveryOther(Node l){
Node l1 = l;while (l1 != null && l1.next != null){
l1.next = l1.next.next;l1 = l1.next;
}return l;
}