C Sc 335 Practice Test 2 Fall 14 Section Leader ______ Name ________________________ 1. Write the output generated by the same code when aNumberMaybe is first "123" and then "NOgOOD" (6pts) String aNumberMaybe = "123"; try { System.out.println("--"); double num= Double.parseDouble(aNumberMaybe); System.out.println("oo"); } catch (NumberFormatException nfe) { System.out.println("++"); } String aNumberMaybe = "NOgOOD"; try { System.out.println("--"); double num = Double.parseDouble(aNumberMaybe); System.out.println("oo"); } catch (NumberFormatException nfe) { System.out.println("++"); } 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, … Pattern Name a. b. … g. Synopsis Provide a way to access the elements of a collection sequentially without revealing the underlying implementation. TBA … TBA 3. The UofA Bookstore has decided that there is just too much traffic in the bookstore at the beginning of each semester. In an effort to reduce in-house traffic, the bookstore has decided to implement an online storefront where students can purchase all of their books online and just pick them up sometime after they’ve been purchased. You are to do some analysis and come up with a model for the bookstore’s new online front. User Stories: o o o o o o o A student may remove 1 to many items from the shelf and place them into a shopping basket A student should be able to remove items from a shopping basket and place them back on the shelf A student should be able to purchase the items in their shopping basket To check out, a student must give their shopping basket to the cashier (there is only one cashier) The cashier creates an order that consists of a item, quantity, and a price based on the item’s ISBN If the CatCard has enough money, the total amount will be deducted and the items will be removed from inventory, a claim check confirmation for the order will be sent to the student’s email address If the CatCard funds are insufficient, place all back on the shelf 3a) List the 4 most important objects to model this system along with the major responsibility: Candidate Object Major Responsibility 3b) Draw a UML class diagram showing all of your candidate objects and any relationships between them. Show inheritance relationships, interface implementation, or general association such as dependency by drawing a line. Write any multiplicity adornment you can think of. You will likely have 1, and or * in a few places at least. Each classes needs the class name and at least one appropriate method (no attributes needed for a perfect score). 1 4. The Command design pattern encapsulates the concept of a command into an object. You can save it for later execution. In the following code, six commands of two different types are constructed and saved in a Vector. Later on, the execute message is sent to all six Command objects. The two classes that you will be asked to write are highlighted in boldface: Command and BorrowCommand. To save time, do not write ReturnCommand. // Have two borrowers and three books to store in the two Command objects Borrower joe = new Borrower("Joe"); Borrower kim = new Borrower("Kim"); Book b0 = new Book("Pascal"); Book b1 = new Book("Java"); Book b2 = new Book("c++"); Command Command Command Command c1 = new BorrowCommand(joe, b0); // Construct a Commmand so Joe borrows Pascal c2 = new BorrowCommand(joe, b1); // Construct a Commmand Joe borrows Java c3 = new BorrowCommand(kim, b2); // ... c4ThatFails = new BorrowCommand(kim, b0); // Nothing will happen later with execute() Command c5 = new ReturnCommand(joe, b0); Command c6Fails = new ReturnCommand(joe, b2); Output: Joe has [] attempts to BORROW Pascal [Joe has [Pascal], Kim has []] List<Command commandList = new ArrayList<Command>(); commandList.add(c1); commandList.add(c2); commandList.add(c3); commandList.add(c4ThatFails); // already out commandList.add(c5); commandList.add(c6Fails); // Doesn't have Joe has [Pascal] attempts to BORROW Java [Joe has [Pascal, Java], Kim has []] Kim has [] attempts to BORROW c++ [Joe has [Pascal, Java], Kim has [c++]] Kim has [c++] attempts to BORROW Pascal [Joe has [Pascal, Java], Kim has [c++]] for(Command ref : commandList) { ref.execute(); System.out.println(borrowerList); System.out.println(); } Joe has [Pascal, Java] attempts to RETURN Pascal [Joe has [Java], Kim has [c++]] Joe has [Java] attempts to RETURN c++ [Joe has [Java], Kim has [c++]] 2 4a) Write Command as if it were in its own file (use the UML class diagram to help) 4b) Complete class BorrowCommand as if it were in its own file. The execute method adjusts the Borrower and the Book if everything is all right. However, if the Book is already borrowed, execute returns false. public class BorrowCommand implements Command { private Borrower theBorrower; private Book theBook; public BorrowCommand(Borrower aBorrower, Book aBook) { theBorrower = aBorrower; theBook = aBook; } public boolean execute() { System.out.println(theBorrower + " attempts to BORROW " + theBook); } public boolean undo() { // a borrow by returning System.out.println(theBorrower + " undo a Borrow" + theBook); 3 5. 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. 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 an array of char 4 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; } // 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++; if (numberOfWrongGuesses() >= MAX_WRONG) timer.stop(); You always get this else { char guess = guesses[tick]; output, System.out.println(guess + " " + tryThisLetter(guess) + one line every second " " + numberOfWrongGuesses()); e false 1 // Tell the HangmanPanel to update the view i true 1 setChanged(); o true 1 notifyObservers(); u false 2 } y true 2 } x false 3 t false 4 k false 5 Using the provided code above, modify HangmanPanel below to do whatever you have to do to draw the correct q false 6 } 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() { } 5 @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 public void update(Observable hangmanGame, Object notUsedHere) { } } 6. Given class Point and a test driver for class Circle and class Rectangle, implement a properly designed inheritance hierarchy in Java (on the next page). Let Shape be the abstract class. Implement all three classes to the right of the non-inheritance version on the next page. Completely implement all constructors and all methods. Include all instance variables. The Circle and Rectangle classes must behave exactly the same with the inheritance hierarchy as without. The assertions must pass. (20pts) @Test public void test getArea() { // 10 pixels over, 10 pixels down, radius 2.0 Shape c = new Circle(10, 10, 2.0); asssertEquals(3.14159, c.getArea(), 0.001); // width = 3.25, height = 5.75 Shape r = new Rectangle(40, 10, 3.25, 5.75); sssertEquals(18.6875, r.getArea(), 0.001); Shape r2 = new Rectangle(40, 60, 2, 3); asssertEquals(6.0, r.getArea(), 0.1); } } 6 public class Point { private int xPos; private int yPos; // Use this type Using good Object-Oriented Design, completely implement the hierarchy here public Point(int x, int y) { xPos = x; yPos = y; } public int getX() { return xPos; } public int getY() { return yPos; } } public class Rectangle { private Point upperLeft; private double width; private double height; public Rectangle(int x, int y, double height, double width) { upperLeft = new Point(x, y); width = width; height = height; } public int getX() { return upperLeft.getX(); } public int getY() { return upperLeft.getY(); } public double getArea() { return width * height; } } public class Circle { private Point upperLeft; private double radius; public Circle(int x, int y, double diameter) { upperLeft = new Point(x,y); radius = diameter / 2; } public int getX() { return upperLeft.getX(); } public int getY() { return upperLeft.getY(); } public double getArea() { return Math.PI*Math.pow(radius, 2); } } 7 7. Given that this code runs on a computer first: ServerSocket serverSocket = new ServerSocket(4000); System.out.println("Waiting . . ."); Socket client = serverSocket.accept(); ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream()); ObjectInputStream input = new ObjectInputStream(client.getInputStream()); String clientInput = (String) input.readObject(); System.out.println("Just read " + clientInput); output.writeObject("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("Output to "); String responseToMyOutput = (String) input.readObject(); System.out.println("Input " + responseToMyOutput); server.close(); 7a) What output does the server code generate? 7b) What output does the client code generate? 8