Practice Test 2 C Sc 335 Spring 2012 SL ______ Name

advertisement
CSc 335 Test 2 Review Sheet followed by Practice Test
o
o
o
o
o
Tuesday 10 April 3:30-4:45 our usual lecture hall
Sit in an aisle, against the wall, or have one empty seat to both your left and right
Worth 18% of your final grade
It is Closed-book and closed-notes
An optional test review session will be held Monday 9-April
Here is a preview of the 8 questions Rick expects to have on the real test
1. Analysis and Design: Given a problem specification: find the objects, write a sequence diagram that
includes message names from the sender to the receiver (return types not needed)
2. Know synopses of the design patterns we discussed: Composite, Singleton, Observer, Singleton,
Strategy, Command, Decorator, Iterator, Factory
3. Write code, interfaces and/or classes for a problem using a Known Design Pattern that we have
presented in class or section: See list above.
4. Write code, interfaces and/or classes for a problem using a Design Pattern not previously discussed in
class or section. One of these: Flyweight, State, or Chain of Responsibility
5. Networking question using Socket and SocketServer and their input and output streams.
6. Drawing: Mostly knowing how to write code in paintComponent, calling repaint from the observers
update method, and what a Timer does for animation. Know draw(Shape) where the classes
implementing Shape are Rectangle2D.Double (x, y, w, h), Ellipse2D.Double(x, y, w,
h), and Line2D.Double(x1, y1, x2, y2). An example of any required shape would be supplied,
so there is no need to memorize shapes. We will also supply the paintComponent method heading
and the cast to Graphics2D.
7. Inheritance Hell Heck Question like handout from 3-April
8. Java Ranch Questions
1
Practice Test 2 C Sc 335 Spring 2012 SL ___________ Name _____________________ 150pts
1. Analyze and begin to design an information system for a video rental store. Simplifying assumptions
and details:







Rents only videos, not computer games or other items.
A “video” can be in any medium: tape, DVD, and so on.
The store does not sell anything. For example, there are no sales of videos or food.
Cash-only payments
This is a real store with a real cashier register were transactions are carried out
On completion of a rental, the customer receives a transaction report with ‘typical’ information on it—use
your judgment.
Each renter has a separate membership
1a) Create an initial list of candidate objects that would do a reasonable job of modeling this system
1b) Write a sequence diagram to represent the objects relationships and messages involved in a scenario that
begins when valid customer arrives at the cashier with one video to rent (assume the store is open and the
cashier is at a cash register).
2. Here are the names of all 23 Object-Oriented Design Patterns cataloged in the GoF book. Factory
Method, Builder, Prototype, Singleton, Adaptor, Bridge, Composite, Decorator, Façade, Flyweight,
Proxy, Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State,
Strategy, Template Method, Visitor. For each synopsis in the right column and write the matching
design pattern name in the left column after each of the letters a. through k.
Pattern Name
a.
b.
k.
Synopsis
Provide a way to access the elements of a collection sequentially without
revealing the underlying implementation.
TBA
TBA
2
3. The composite design pattern composes objects into tree structures to represent part-whole
hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. Here
is the general form of the Composite Design Pattern:
In a real world example of composing a drawing (actually a bunch of instructions for a drawing), the
following client code should generate the output shown:
Primitive p = new Primitive("Blue Line");
p.add(new Primitive("?Blue dot?"));
// Should print: 'Cannot add to a PrimitiveElement'
System.out.println();
// Create a tree structure to represent a composite drawing element
Composite root = new Composite("Picture");
root.add(new Primitive("Red Line"));
root.add(new Primitive("Blue Circle"));
root.add(new Primitive("Green Box"));
Composite comp = new Composite("Two Circles");
comp.add(new Primitive("Black Circle"));
comp.add(new Primitive("White Circle"));
root.add(comp);
// Add one more Primitive drawing element
Primitive yl = new Primitive("Yellow Line");
root.add(yl);
// Recursively display nodes
root.display();
Desired Output
'Cannot add to a PrimitiveElement'
draw Picture
draw Red Line
draw Blue Circle
draw Green Box
draw Two Circles
draw Black Circle
draw White Circle
draw Yellow Line
3
3a) Draw the UML Diagram to capture the real world example of Primitive and Composite drawing elements
o
o
o
o
List all class names using italics for abstract classes
Draw all relationships
Place the add methods in the correct places using italic when abstract
Place the display methods in the correct places using italic when abstract
3b) Using your UML diagram write the abstract class
3c) Using your UML diagram write the Primitive and Composite classes so your code represents the Composite
as specified (need recursion in one method) and your output matches.
4
4. Write code, interfaces and/or classes for a problem using a Design Pattern not previously discussed in class
or section. One of these: Adapter, Proxy, Mediator, State, or Chain of Responsibility.
Question not given for obvious reasons. It would look like the one above.
There may only be one Design Pattern Question on the test if Rick thinks it would be too much
5. Given that this code runs on a computer first:
ServerSocket serverSocket = new ServerSocket(4000);
System.out.println("This server now awaits one client");
Socket client = serverSocket.accept();
ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream input = new ObjectInputStream(client.getInputStream());
String clientInput = (String) input.readObject();
System.out.println("Client wrote: " + clientInput);
output.writeObject("This server is shutting down.");
client.close();
and then the following code starts on the same computer
Socket server = new Socket("localhost", 4000);
ObjectOutputStream output = new ObjectOutputStream(server.getOutputStream());
ObjectInputStream input = new ObjectInputStream(server.getInputStream());
output.writeObject("I am a client");
String responseToMyOutput = (String) input.readObject();
System.out.println("Server wrote: " + responseToMyOutput);
server.close();
5a) What output does the server code generate?
5b) What output does the client code generate?
6. In the game of hangman, you are to guess a word by selecting letters. One part of the game is to have an
image appears like this when the game begins:
For each wrong guess, another line is drawn on the hangman illustration. You lose if the drawing is finished
before you've worked out the word. Using the code provided below (and a start to HangmanPanel), modify
HangmanPanel to do whatever you have to do to draw the correct number of pieces of the hangman in the order
shown. This may involve adding a new method, instance variable, or even a separate class.
5
1. Head
2. Body
3. Left arm
4. Right arm
5. Left leg
6. Right leg
Note: Hangman model (see other side of this page) has already been programmed to stop at 6 incorrect guesses
(and because there is no human input, the game draw all 6 pieces).
// This controller starts a game when HangmanModel is constructed.
// This code also ensures HangmanPanel is observing the game.
public class HangmanMAIN extends JFrame {
public static void main(String[] args) {
new HangmanMAIN().setVisible(true);
}
private HangmanPanel hangmanPanel;
public HangmanMAIN() {
setTitle("Hangman");
setSize(250, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hangmanPanel = new HangmanPanel();
add(hangmanPanel);
HangmanModel game = new HangmanModel();
game.addObserver(hangmanPanel);
}
}
// This simple HangmanModel has only one word that can be guessed at.
// And it makes the same guesses based on letters in a an array of char
public class HangmanModel extends Observable implements ActionListener {
private int numberWrong;
private String theWordToGuess;
private Timer timer;
private int tick;
public static final int MAX_WRONG = 6;
// This game will have the exact guesses each time. FOR DEMO ONLY
public static final char[]
// Note: q is the last wrong guess
guesses = { 'a', 'e', 'i', 'o', 'u', 'y', 'x', 't', 'k', 'q' };
public HangmanModel() {
numberWrong = 0;
theWordToGuess = "polymorphism";
timer = new Timer(1000, this); // Make a "guess" every second
tick = 0;
timer.start();
}
public int numberOfWrongGuesses() {
return numberWrong;
}
6
// Return true if a guess (ch) is in the string "polymorphism"
// If not, add 1 to the number of wrong guesses
public boolean tryThisLetter(char ch) {
if (theWordToGuess.indexOf(ch) >= 0)
return true;
else {
numberWrong++;
return false;
}
}
// Every second, get the next character from guesses (an array of char)
// and try it. The time stops when MAX_WRONG incorrect guesses are made
// (and in this game with no user input, the guesses are always the same.
public void actionPerformed(ActionEvent timerTick) {
tick++;
You always get this output,
one line every second
if (numberOfWrongGuesses() >= MAX_WRONG)
timer.stop();
else {
char guess = guesses[tick];
System.out.println(guess +
" " + tryThisLetter(guess) +
" " + numberOfWrongGuesses());
// Tell the HangmanPanel to update the view
setChanged();
notifyObservers();
}
e
i
o
u
y
x
t
k
q
false 1
true 1
true 1
false 2
true 2
false 3
false 4
false 5
false 6
}
}
Using the provided code above, modify HangmanPanel below to do whatever you have to do to draw the
correct number of pieces of the hangman in the order shown. This may involve adding a new method, instance
variable, or even a separate class.
public class HangmanPanel extends JPanel implements Observer {
public HangmanPanel() {
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// Always draw the gallows and the noose at startup
System draws
g2.fill(new Rectangle2D.Double(5, 230, 200, 5)); // base of scaffold
g2.fill(new Rectangle2D.Double(5, 10, 5, 225)); // side of scaffold
this at start up
g2.fill(new Rectangle2D.Double(5, 5, 80, 5));
// top of scaffold
g2.draw(new Line2D.Double(new Point(80, 10), new Point(80, 30))); // noose
7
public void update(Observable hangmanGame, Object ignored) {
}
}
Java Ranch Questions
Answer Questions for 7 after reading as many of the 161 questions as possible at
http://www.javaranch.com/game/game2.jsp and reading these tips:
o
o
o
You should know most (except a few things like bit shifting, synchronized, volatile)
 If the question feels really obscure, it probably won't be on the quiz
 Specifically: there will be no bit shifting questions, no need to know these operators
~(invert) <<(shiftleft) >>(right) &(and) ^(XOR)
|(OR)
You may learn and/or relearn a few new things about Java
Topics you may need to further explore (inspired by Java Certification Questions)

Java 6's switch statement (switch argument must be int-compatible, byte, short, char, and
int and Enums
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
// …
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}







Overriding methods cannot throw new or broader exceptions
A static class can be used from outside the class. Example: Recangle2D.Double needs to be
static in order to be instantiated outside of Rectangle2D
Java promotion: widening allowed (int to long as in long lg = 1234) , narrowing only with
cast (double to float or float to int as in int i = (int)3.5f
Override private methods? No, but it looks that way when redeclared
Can't reduce scope when overriding methods. A protected method can be overridden as public,
buy not reduced to package or private.
Division by 0 different for ints vs. doubles 5/0 is an error, 5.0/0 evaluates to infinity
A finally block always executes after the try and/or catch block finishes, even if there is no
exception thrown. This allows cleanup code to always execute
ServerSocket ss = new ServerSocket(0);
try {
Socket socket = ss.accept();
// ...
}
finally {
ss.close(); // frees the port for later use no matter what happens in try
}
8

post increment, pre increment during assignment.
int y = 3;
int x = 0;
x = y++;
assertEquals(3,
assertEquals(4,
x = ++y;
assertEquals(5,
assertEquals(5,
x);
y);
x);
y);
7. Check the correct answer with an X, 0.5 pts each (there will be ~30 questions)
a. All Java keywords are written in lower case.
__tr
__false
b. Does a call to System.gc() force garbage collection to take place?
__ yes always
__ not always
c. Assume: byte a = 3; byte b = 2;
____ compile time error
____ c == 5
____ c == 3
____ runtime exception
byte c;
What is the result of c = a + b;
8. Inheritance Heck
 Lecture Handout (should have answers from lecture, but will include in answers for this
o http://www.cs.arizona.edu/~mercer/Misc/3-April-AdvancedInheritance.pdf or doc
 Section Handout (answers given)
o http://www.cs.arizona.edu/~mercer/Sections/335/SectionInheritanceHeck.pdf
Note: The Java Code with 4 classes in an inheritance hierarchy is the last page of this test. Please tear it off and
use it to answer the questions that follow
8a) Draw the inheritance hierarchy see lecture handout
8b) Show output in table with classes in columns and methods in rows. Use / for new lines. Write X instead of
the output if the class does not have that particular method.
8c) Write CE, RE or output:
see lecture handout
9
Tear this page off to help answer the previous questions
Use the following Java code to answers questions 8a, 8b, and 8c
class A {
public void A1 {
}
}
// … TBA
10
Download