2008S2ExamAnswers

2008S2ExamAnswers - COMPSCI 101 THE UNIVERSITY OF AUCKLAND...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: COMPSCI 101 THE UNIVERSITY OF AUCKLAND SECOND SEMESTER, 2008 Campus: City COMPUTER SCIENCE Principles of Programming (Time allowed: TWO hours) NOTE: Attempt ALL questions Write your answers in the space provided There is space at the back for answers that overflow the allotted space No calculators are permitted Surname: Forenames: Student ID number: Login name: Q1 Q4 (/32) Q2 Q7 (/7) Q5 (/11) Q3 (/7) Q8 (/7) Q6 (/6) Q10 Q11 (/7) Q9 (/7) (/6) (/7) Total (/3) /100 CONTINUED -2Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 1 (32 marks) a) What is the output produced by the following code? System.out.println("Min is: " + Math.min(1, Math.min(0, -1))); Min is: -1 (2 marks) b) What is the output produced by the following code? int value = 13; System.out.println( ! (6 < value) ); false (2 marks) c) What is the output produced by the following code? int i = 5; int numbers = {4, 2, -7, 5, 1, 6, 3}; System.out.println(numbers[i] + numbers[i+1]); 9 (2 marks) CONTINUED -3Question/Answer Sheet COMPSCI 101 I D: ..................................................................... d) What is the output produced by the following code? String name = "intuitive"; name = name.substring(2); int position = name.indexOf('i'); System.out.println(name.substring(0, position + 1)); tui (2 marks) e) What is the output produced by the following code? double d = 23.7, e = 3.1; System.out.println((int)(Math.round(d - e))); 21 (2 marks) f) Complete the output which is produced by the following code. Point p1 = new Point(4, 6); Point p2 = new Point(3, 5); p1.move(10, 4); p2.translate(10, 4); System.out.println("1: " + p1.x + ", " + p1.y); System.out.println("2: " + p2.x + ", " + p2.y); 1: 10, 4 2: 13, 9 (2 marks) CONTINUED -4Question/Answer Sheet COMPSCI 101 I D: ..................................................................... g) Complete the output which is produced by the following code. Point p1 = new Point(4, 6); Point p2 = new Point(4, 6); Point p3 = p2; p2 = new Point(p3.x, p3.y); System.out.println("1: " + p1.equals(p2)); System.out.println("2: " + (p2 == p3)); 1: true 2: false (2 marks) h) What is the output produced by the following code? Rectangle rect = new Rectangle(20, 30, 50, 40); Point p = new Point(rect.x + 5, rect.y + 2); if (rect.contains(p)) { System.out.println("Yes"); } else { System.out.println("No"); } yes (2 marks) CONTINUED -5Question/Answer Sheet i) COMPSCI 101 I D: ..................................................................... Complete the following code so that it produces the output: No Rectangle rect1 = new Rectangle(20, 30, 50, 40); Rectangle rect2 = new Rectangle(10, 20, 8 , 5 ); One of the values less than 10 if (rect1.intersects(rect2)) { System.out.println("Yes"); } else { System.out.println("No"); } (2 marks) j) What is the output when the start() method below is executed? public void start() { Point p1 = new Point(3, 5); doSomething(p1); System.out.println("1: " + p1.x + ", " + p1.y); } private void doSomething(Point p) { p.x = p.x + 10; System.out.println("2: " + p.x + ", " + p.y); } 2: 13, 5 1: 13, 5 (2 marks) CONTINUED -6Question/Answer Sheet COMPSCI 101 I D: ..................................................................... k) Declare a constant for the Greek letter pi and assign to it the value 3.14159. final double PI = 3.14159; (2 marks) l) Write a while loop that adds together the first n positive integers, i.e., 1 + 2 + 3 + ... + n and stores the result in the variable, sum. int sum = 0; for(int i=1; i<=n; i++) { sum = sum + i; } (2 marks) m) Rewrite the following “while” loop into an equivalent “for” loop. int i = 0; while (i < exp) { total = total * base; i++; } for(int i=1; i<exp; i++) { total = total * base; } (2 marks) CONTINUED -7Question/Answer Sheet COMPSCI 101 I D: ..................................................................... n) Declare a String array variable, months. String months; (2 marks) o) Construct the months array declared in n) above, so that it is large enough to hold the names of all the months, one name per element. months = new String[12]; (2 marks) p) Why don't you need to worry about aliasing when dealing with String objects? Strings are immutable (2 marks) CONTINUED -8Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 2 (11 marks): Complete each of the methods below as specified in the comment preceding each method. a) //method to return an int twice as large as n private int twice(int n){ return 2*n; } (2 marks) b) //method to decide whether n1 and n2 are in ascending //order (or of equal value) private boolean areInOrder(int n1, int n2){ return n1 <= n2; } (2 marks) c) //method to tell whether one String, s1, has the same //last character as another String, s2 private boolean sameFinish(String s1, String s2){ int lastS1 = s1.length()-1; int lastS2 = s2.length()-1; return s1.charAt(lastS1) == s2.charAt(lastS2); } (3 marks) CONTINUED -9Question/Answer Sheet COMPSCI 101 I D: ..................................................................... d) //method to replicate a String, s, the number of //times given by the int, n. For example //reiterate("ho", 3) should return "hohoho" private String reiterate(String s, int n){ result = ""; for (int i=0; i<n; i++){ result = result + s; } return result; } (4 marks) CONTINUED - 10 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 3 (6 marks) Complete the output produced when the following start() method is executed. public void start() { int n = 1; String s = "Hello World"; String car = new String[3]; car[2] = "Morgan"; method1(n, s, car); System.out.println("n: " + n); System.out.println("s: " + s); System.out.println("car[2]: " + car[2]); } private void method1(int i, String word, String name) { i = 3; word = "Goodbye"; name[2] = "Corvette"; } n: 1 s: Hello World car[2]: Corvette (6 marks) CONTINUED - 11 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 4 (7 marks) a) Given the array definition below: String monthNames = { "January", "February", "March", "April", "May", "June", "July", "August", "September","October", "November", "December" }; what is printed by the following statement? System.out.println(monthNames[6]); July (2 marks) b) Complete the printShortestMonth() method, which looks at each element in the String array, months, and prints the element with the fewest letters in its name. private void printShortestMonth(String months) { String shortest ""; for(int i=0; i<months.length; i++) { if (months[i].length() < shortest.length()) { shortest = months[i]; } } System.out.println(shortest); } (5 marks) CONTINUED - 12 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 5 (7 marks): As accurately as possible, show what would be drawn in the window by the following program. Grid lines have been drawn on the window to help you. The gap between adjacent gridlines is 10 pixels. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyJPanel extends JPanel { public void paintComponent(Graphics g){ super.paintComponent(g); drawThing(g, 20, 40, 20); } public void drawThing(Graphics g, int x, int y, int size) { g.drawOval(x, y, size * 2, size * 2); g.drawLine(x, y + size * 3, x + size * 2, y + size * 2); g.fillRect(x + size / 2, y + size * 3, size, size); g.drawString("101", x + size * 3 / 2, y + size * 4); } } CONTINUED - 13 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... (7 marks) CONTINUED - 14 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 6 (7 marks): Complete the getAverageHeight() method which has one parameter, an array of Rectangle objects. The method returns the average height of the Rectangles in the parameter array. public void start() { Rectangle rects = { new Rectangle(20, 30, 50, 40), new Rectangle(50, 60, 10, 20), new Rectangle(10, 90, 20, 45) }; double average = getAverageHeight(rects); System.out.println("Average height: " + average); } When the above start() method is executed with the completed getAverageHeight() method the output is: Average height: 35.0 Notes: The Rectangle array passed as a parameter may have any number of elements. You may assume that there is at least one element in the parameter array and that none of the elements are null. CONTINUED - 15 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... private double getAverageHeight(Rectangle rects){ double average = 0; double sum = 0; for(int i=0; i<rects.length; i++) { sum = sum + rects[i].height; } average = sum / rects.length; return average; } (7 marks) CONTINUED - 16 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 7 (7 marks) The following JPanel responds to MouseEvents. Initially the JPanel displays a filled rectangle on the right hand side of the window, referred to as the base rectangle. When the user presses the mouse, a red horizontal bar is displayed from the base rectangle to the x position where the user pressed the mouse. If the user presses the mouse inside the base rectangle or to the right of the base rectangle, the horizontal bar should not appear in the JPanel. The following screen shots show the behaviour of the completed JPanel. The following 14 statements are part of the code. Place each number in the correct place in the AJPanel definition on the next page so that the JPanel executes as described above. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. MouseEvent e implements MouseListener repaint(); private int barLeft; addMouseListener(this); Graphics g public void mouseClicked(MouseEvent e) {} barLeft = e.getX(); extends JPanel import java.awt.event.*; if (barLeft >= BASE_LEFT) { barLeft = BASE_LEFT; } barLeft = BASE_LEFT; g. fillRect(barLeft, BAR_Y, barWidth, BAR_HEIGHT); int barWidth = BASE_LEFT - barLeft; CONTINUED - 17 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... import java.awt.*; import javax.swing.*; 10 9 public class AJPanel 2 { private static final int BAR_Y = 60; private static final int BAR_HEIGHT = 20; private private private private static static static static final final final final int int int int BASE_TOP = BAR_Y - 40; BASE_LEFT = 350; BASE_HEIGHT = 100; BASE_WIDTH = 10; 4 public AJPanel() { 5 12 } public void mousePressed( 1 ){ 8 11 3 } public void paintComponent( 6 ){ super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(BASE_LEFT, BASE_TOP, BASE_WIDTH, BASE_HEIGHT); 14 g.setColor(Color.RED); 13 } 7 public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvente){} public void mouseExited(MouseEvent e){} } (7 marks) CONTINUED - 18 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 8 (7 marks): The JPanel defined on the next page contains one JTextField component and two JButton components: valueT – a JTextField which contains an int value, increaseB – a JButton displaying the String, “INCREASE”, decreaseB – a JButton displaying the String, “DECREASE”. Below is a screenshot of the JPanel when it is first displayed. The valueT JTextField displays the number 0. When the user presses the "INCREASE" JButton, the value in the valueT JTextField increases by a random number between 1 and 5 (inclusive). When the user presses the "DECREASE" JButton, the value in the valueT JTextField decreases by a random number between 1 and 5 (inclusive). You are required to complete the JPanel definition on the next page so that the JPanel behaves as described above. You MUST use the variables given in the code. The screenshots below show an example of the JPanel when the user presses the "INCREASE" JButton twice and then presses the "DECREASE" JButton twice. CONTINUED - 19 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AJPanel extends JPanel implements ActionListener { { private JTextField valueT; private JButton increaseB, decreaseB; public AJPanel() { valueT = new JTextField(5); increaseB = new JButton("INCREASE"); decreaseB = new JButton("DECREASE"); add(increaseB); add(valueT); add(decreaseB); increaseB.addActionListener(this); decreaseB.addActionListener(this); valueT.setText("0"); } public void actionPerformed(ActionEvent e) { int num = (int)(Math.random() * 5 + 1); int value = Integer.parseInt(valueT.getText()); if(e.getSource() == increaseB) { value = value + num; } else { value = value - num; } valueT.setText("" + value); } } (7 marks) CONTINUED - 20 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 9 (3 marks): The Time24Hour class has two int instance variables, hour and minutes. Complete the equals() method for the Time24Hour class. This method returns true if both objects represent the same time, false otherwise. public boolean equals(Time24Hour other) { return hour == other.hour && minutes == other. minutes; } (3 marks) CONTINUED - 21 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 10 (6 marks): In the following Bank class: public class Bank { //put instance variables here private Person manager; private Time24Hour openingTime; private int maxTellers; public Bank(Person manager, Time24Hour openTime, int tellers) { //put the constructor code here this.manager = manager; openingTime = openTime; maxTellers = tellers; } ... other code omitted ... } (6 marks) a) declare three instance variables: an instance variable, manager, of type Person, an instance variable, openingTime, of type Time24Hour, specifying the bank opening time, and an instance variable, maxTellers, of type int, specifying the maximum number of teller positions. b) complete the constructor which has the following 3 parameters: a Person parameter which specifies the person who is the manager, a Time24Hour object which specifies when the bank opens, and an int which specifies the maximum number of tellers. CONTINUED - 22 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... Question 11 (7 marks) You are required to complete the following JPanel which uses a Timer object. The Timer object is created with a delay of 100 milliseconds. Initially nothing is displayed inside the JPanel except a thin rectangle down the right hand side of the window. The Timer starts when the user first presses the UP arrow key. When the Timer starts, a black line, which increases in length, appears from the left hand side of the JPanel. The length of the line increases by ten pixels with each tick of the Timer, i.e. the end of the line increases by ten pixels each time as the line grows to the right. When the end of the line reaches 200, the line starts shrinking, i.e. the end of the line decreases by ten pixels. When the length of the line is zero, the line starts growing again. By pressing the UP and DOWN arrow keys, the user controls when the line starts and stops growing/shrinking. When the user presses the UP arrow key, the Timer should start and the line continues growing/shrinking. When the user presses the DOWN arrow key, the Timer should stop. When the user presses the UP arrow key again, the Timer starts again and the line continues growing/shrinking, etc. Below are some screenshots of the JPanel in action. The first screenshot shows the JPanel when it is first displayed. The next five screenshots show the JPanel after the user has pressed the UP arrow key and the line has started growing. … … … … The next three screenshots show the line shrinking after the end of the line has reached 200 pixels. … … … The last two screenshots show the line growing again after the end of the line has shrunk to 0 pixels. … … Notes: The start of the line is ALWAYS given by the constants: public static final int LINE_LEFT = 0; public static final int LINE_DOWN = 50; You MUST use the variables and constants given in the code. When the user first presses the UP arrow key the line starts increasing its length. CONTINUED - 23 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AJPanel extends JPanel implements ActionListener, KeyListener { //The start of the line public static final int LINE_LEFT = 0; public static final int LINE_DOWN = 50; private int lineEnd; private boolean isIncreasing; private Timer t; public AJPanel() { isIncreasing = true; lineEnd = LINE_LEFT; t = new Timer(100, this); addKeyListener(this); } public void actionPerformed(ActionEvent e) { if (isIncreasing) { lineEnd = lineEnd + 10; if (lineEnd >= 200) { isIncreasing = false; } } else { lineEnd = lineEnd - 10; if (lineEnd <= LINE_LEFT) { isIncreasing = true; } } repaint(); } CONTINUED - 24 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { t.start(); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { t.stop(); } } public void paintComponent(Graphics g) { super.paintComponent(g); //the thin rectangle displayed on the right //hand side of the window g.fillRect(200, 0, 4, 150); g.drawLine(LINE_LEFT, LINE_DOWN, lineEnd, LINE_DOWN); } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} } (7 marks) CONTINUED - 25 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... OVERFLOW PAGE (If you have used this page, please indicate clearly under the relevant question that you have overflowed to this page) CONTINUED - 26 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... OVERFLOW PAGE (If you have used this page, please indicate clearly under the relevant question that you have overflowed to this page) CONTINUED - 27 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... ROUGH WORKING (WILL NOT BE MARKED) (You may use this page for rough working) CONTINUED - 28 Question/Answer Sheet COMPSCI 101 I D: ..................................................................... ROUGH WORKING (WILL NOT BE MARKED) (You may use this page for rough working) ...
View Full Document

This note was uploaded on 03/01/2012 for the course COMPSCI 101 taught by Professor Adrianaferraro during the Summer '12 term at Auckland.

Ask a homework question - tutors are online