THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City...

28
THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE: You must answer all questions in this test. No calculators are permitted Answer in the spaces provided in this booklet. There is space at the back for answers that overflow the allotted space. Surname Forenames Student ID Login (UPI) Q1 (/8) Q4 (/8) Q7 (/12) Q10 (/15) Q2 (/6) Q5 (/12) Q8 (/8) TOTAL /100 Q3 (/6) Q6 (/12) Q9 (/13)

Transcript of THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City...

Page 1: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

THE UNIVERSITY OF AUCKLAND

SUMMER SEMESTER, 2013

Campus: City

COMPUTER SCIENCE WITH ANSWERS

Principles of Programming

(Time Allowed: TWO hours)

NOTE: You must answer all questions in this test. No calculators are permitted Answer in the spaces provided in this booklet. There is space at the back for answers that overflow the allotted space.

Surname

Forenames

Student ID

Login (UPI)

Q1

(/8)

Q4

(/8)

Q7

(/12)

Q10

(/15) Q2

(/6)

Q5

(/12)

Q8

(/8)

TOTAL

/100

Q3

(/6)

Q6

(/12)

Q9

(/13)

Page 2: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 2 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 1 (8 marks)

a) What is the output produced by the following code?

System.out.println(2 + 5 * 2 + ", " + 7 % (3 + 2) + 1);

12, 21

(2 marks)

b) The displayBill() method is shown below:

private void displayBill(int base, boolean withColour,

boolean withCut) {

int cost = base;

if (withColour || withCut) {

cost = cost + 60;

}

System.out.println("Total cost $" + cost);

}

In the space below, complete the call to the displayBill() method so that the method

displays the following output: Total cost $110

//There are many other solutions //to this question displayBill( 50, true, false);

(2 marks)

Page 3: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 3 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

c) Complete the output produced by the following code.

String word = "IMMATERIAL";

int pos = word.indexOf("M");

String result = word.substring(pos, pos + 3);

System.out.println("pos: " + pos + " result: " + result);

pos: 1 result: MMA

(2 marks) d) Complete the following Java statement which assigns a random number that is either 4, 5 or 6

to the int variable, number.

int number = (int)(Math.random() * 3 + 4);

(2 marks)

Page 4: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 4 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 2 (6 marks)

a) The following section of code displays the following output: result: true

In the spaces provided below, assign values to the int variable c and to the int variable d so that the output is as shown above.

int a = 8; boolean b = false; //There are many other

//solutions to this question

int c = int d =

(2 marks)

boolean result = ! ( (c > d || b) && c > a ); System.out.println("result: " + result);

b) What is the output when the following program is executed?

public class Program {

public void start() {

lotsOfIfs(2, 3); }

private void lotsOfIfs(int x, int y) {

if (x < y && y > 4) {

if (y != 6) {

System.out.print("A ");

} else {

System.out.print("B "); }

} else if (y < 0) {

System.out.print("C ");

} else {

if ( ! (y < 4) ) {

System.out.print("D "); }

System.out.print("E "); } } }

4

6

Page 5: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 5 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

E

(2 marks)

c) What is the output when the following program is executed?

public class Program {

public void start() {

lotsOfIfs(2, 5); }

private void lotsOfIfs(int x, int y) {

if (x + y < 8 && (x != y)) {

if (y > x && x != 12) {

System.out.print("A ");

} else {

System.out.print("B "); }

System.out.print("C ");

} else {

if (x >= 0 && ! (x < 7)) {

System.out.print("D ");

} else {

System.out.print("E "); }

System.out.print("F ");

}

if (y > x * 2) {

System.out.print("G "); } } }

A C G

(2 marks)

Page 6: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 6 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 3 (6 marks)

a) Complete the output produced by the following program.

public class Program {

public void start() {

int num = 0;

int end = 15;

for (num = 5; num < end; num = num + 5) {

end = end - 3;

}

System.out.println("num: " + num + " end: " + end);

}

}

num: 15 end: 9

(2 marks)

b) Complete the for loop so that the output is exactly: 44 40 36 32 28 24

//There are other solutions to this question

for( ) { ) {

System.out.print(i + " "); }

(2 marks)

int i = 44; i > 20; i = i - 4

Page 7: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 7 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

c) When the following program is executed:

public class Program {

public void start() {

String input = "";

char c = 'a';

int count = 0;

while (c != 's') {

System.out.print("Enter a word: ");

input = Keyboard.readInput();

c = input.charAt(input.length() - 1);

count++;

}

System.out.println("count: " + count);

}

}

the output is as shown below, except that, in the output below, the user input is not shown. In the spaces provided write two possible user inputs which make the program execute as shown below.

//There are other solutions to this question Enter a word:

Enter a word:

count: 2

(2 marks)

cat

cats

Page 8: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 8 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 4 (8 marks)

a) Complete the getIntFromBarcode() method which is passed a String parameter,

barcode. The method returns the int value from the digits in positions 5, 6 and 7 of the String parameter. For example, the following code:

int result = getIntFromBarcode("9 013456789");

System.out.println("9 013456789: " + result);

result = getIntFromBarcode("8 298170574");;

System.out.println("8 298170574: " + result);

result = getIntFromBarcode("6 100034561");;

System.out.println("6 100034561: " + result);

produces the following output:

9 013456789: 456

8 298170574: 170

6 100034561: 34

private int getIntFromBarcode(String barcode) {

String code = barcode.substring(5, 8); int number = Integer.parseInt(code); return number; }

(4 marks)

Page 9: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 9 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

b) Complete the isEnoughCoins() method which is passed a double followed by three int parameters:

cost – the cost of the item dollar2 – the number of $2 coins, dollar1 – the number of $1 coins,

and fiftyCents – the number of $0.50 coins.

The method returns true if the total value of all the coins is greater than or equal to the cost, otherwise the method returns false. For example, the following code:

boolean haveEnough = isEnoughCoins(3.45, 1, 1, 3); System.out.println("Has paid enough coins: " + haveEnough); haveEnough = isEnoughCoins(31.45, 5, 3, 3); System.out.println("Has paid enough coins: " + haveEnough); haveEnough = isEnoughCoins(10.5, 0, 0, 21); System.out.println("Has paid enough coins: " + haveEnough);

produces the following output:

Has paid enough coins: true

Has paid enough coins: false

Has paid enough coins: true

private boolean isEnoughCoins(double cost, int dollar2, int dollar1, int fiftyCents) {

double total = dollar2 * 2 + dollar1 +

fiftyCents / 2.0; return total >= cost; }

(4 marks)

Page 10: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 10 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 5 (12 marks)

a) What is the output when the following program is executed?

public class Program {

public void start() {

int[] nums = { 6, 9, 3, 7, 4, 6, 0, 8, 4 };

processElements(nums);

}

private void processElements(int[] a) {

int toPrint;

int moveRight = 0;

int moveLeft = a.length - 1;

while (moveRight < moveLeft) {

toPrint = Math.min(a[moveRight], a[moveLeft]);

System.out.print(toPrint + " ");

moveRight++;

moveLeft--;

}

}

}

4 8 0 6

(4 marks)

Page 11: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 11 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

b) The output of the ArrayProgram program is:

Size of the array: 7

5 6 5 In the space provided below, complete the definition of the array, a, so that the output is EXACTLY as shown above.

public class ArrayProgram {

public void start() { //There are other solutions to this question

int[] a = { 5, 6, 5, 3, 4, 7, 0};

(4 marks)

System.out.println("Size of the array: " + a.length);

printSome(a, 4, 7);

}

private void printSome(int[] nums, int low, int high) {

for (int i = 0; i < nums.length; i++) {

if (nums[i] > low && nums[i] < high) {

System.out.print(nums[i] + " ");

}

}

}

}

Page 12: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 12 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

c) Complete the getAverageOfPositives() method which is passed an integer array as a

parameter. The method returns the average of all the positive elements (i.e., elements with a value greater than 0) in the array. For example, the following code:

int[] nums1 = { -1, 3, 5, -4, 0 };

int[] nums2 = { -6, 3, 2, -4, 10 };

int[] nums3 = { 2, 1, -5, 4, -56, 2 };

System.out.println(getAverageOfPositives(nums1));

System.out.println(getAverageOfPositives(nums2));

System.out.println(getAverageOfPositives(nums3));

produces the following output:

4.0

5.0

2.25

You can assume that the parameter array will always have at least one positive element.

private double getAverageOfPositives(int[] nums) { int number = 0; double sum = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { number++; sum = sum + nums[i]; } } double average = sum / number; return average;

Page 13: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 13 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

}

(4 marks)

Page 14: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 14 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 6 (12 marks)

Complete the definition of the Movie class on the next page. The following section of code uses the Movie class to first create three Movie objects and then calls various instance methods on the three objects:

Movie m1 = new Movie("Skyfall", 143);

Movie m2 = new Movie("Argo", 120);

Movie m3 = new Movie("Food Inc.", 94);

System.out.println("1. " + m1.toString());

System.out.println("2. " + m2.toString());

m3.setIsADoco(true);

m2.setTitle("Skyfall");

if ( m2.getIsADoco() ) {

System.out.println("3. Documentary");

} else {

System.out.println("3. Not a documentary");

}

if ( m1.isLongerThan(m2) ) {

System.out.println("4. m1 is longer");

} else {

System.out.println("4. m1 is not longer");

}

if ( m1.hasSameTitle(m2) ) {

System.out.println("5. same title");

} else {

System.out.println("5. not the same title");

}

System.out.println("6. " + m2.toString());

System.out.println("7. " + m3.toString()); Each Movie object stores a title, length (in minutes) and whether it is a documentary or not.

• The setTitle()method is the mutator method for the title instance variable. • The setIsADoco() and getIsADoco() methods are the accessor and mutator methods

for the isADoco instance variable. • The hasSameTitle()method should return true if the object on which the method is

called has the same title as the object passed to the method as a parameter, otherwise it should return false.

Page 15: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 15 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

• The isLongerThan() method should return true if the object on which the method is called is a longer movie than the object passed to the method as a parameter, otherwise it should return false.

• The toString() method should return a text-based representation of the Movie object.

Complete the definition of the Movie class so that when the above section of code executes, the output is identical to that shown below:

1. Skyfall (143)

2. Argo (120)

3. Not a documentary

4. m1 is longer

5. same title

6. Skyfall (120)

7. Food Inc. (94) Documentary

public class Movie {

private int length;

private String title;

private boolean isADoco;

public Movie(String title, int minutes) {

length = minutes;

this.title = title;

isADoco = false;

}

public void setTitle(String title) { this.title = title; }

public void setIsADoco(boolean doco) { isADoco = doco; }

Page 16: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 16 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

public boolean getIsADoco () {

return isADoco; }

public boolean hasSameTitle(Movie other) {

return title.equals(other.title);

}

public boolean isLongerThan(Movie other) {

return length > other.length;

}

public boolean toString() {

String info = title + " (" + length + ")"; if (isADoco) { info = info + " Documentary"; } return info; }

} (12 marks)

Page 17: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 17 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 7 (12 marks)

a) Complete the following definition of the Rectangle object r3 so that the following code outputs true.

Rectangle r1 = new Rectangle(10, 20, 30, 40);

Rectangle r2 = new Rectangle(20, 40, 40, 50); //There are other solutions to this question

Rectangle r3 = new Rectangle( 10, 20, 5, 5 );

(2 marks) System.out.println( r3.intersects(r1) && !r3.intersects(r2) );

b) Give the output produced by the following code.

Rectangle r = new Rectangle(20, 50, 40, 40);

Point p1 = new Point(50, 65);

Point p2 = new Point(p1);

p1.translate(20, 0);

if (r.contains(p1)) {

System.out.print("A ");

} else if (r.contains(p2)) {

System.out.print("B ");

}

p2.x = p2.x + 20;

if (p1.equals(p2)) {

System.out.print("C ");

if (p1 == p2) {

System.out.print("D ");

}

} else {

System.out.print("E ");

}

B C

(2 marks)

Page 18: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 18 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

c) Complete the containsAllPoints() method below. This method takes an array of Point objects, points, and a Rectangle, rect, as parameters, and returns true if every Point in the points array is inside rect; otherwise the method returns false. You may assume the array is full.

private boolean containsAllPoints(Point[] points,

Rectangle rect){ boolean containsAll = true; for (int i = 0; i < points.length; i++) { if (!rect.contains(points[i])) { containsAll = false; } } return containsAll; }

(4 marks)

Page 19: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 19 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

d) Complete the rectanglesAtPoints() method below. This method takes an array of Point objects, points, and an integer, size, as parameters and returns an array of Rectangle objects named rects – one for each Point in the points array – such that each Rectangle is a square of size size, centred at the corresponding point. You may assume the points array is full.

private Rectangle[] rectanglesAtPoints(Point[]

points, int size){ Rectangle[] rects = new

Rectangle[points.length];

for (int i = 0; i < rects.length; i++) {

rects[i] = new Rectangle(points[i].x - size/2, points[i].y – size/2,

size, size); } return rects; }

(4 marks)

Page 20: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 20 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 8 (8 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 javax.swing.*;

public class MyJPanel extends JPanel {

public void paintComponent(Graphics g){

super.paintComponent(g);

drawLogo(g, 20, 20, 20);

}

public void drawLogo(Graphics g, int left, int top,

int size) { for (int i = 0; i < 3; i++) {

if (i % 2 == 0) {

g.fillRect(left + i * size, top + i * size,

size, size);

} else {

g.drawRect(left + i * size, top + i * size,

size, size);

}

}

g.drawOval(left + size, top + size, size, size);

g.drawLine(left + size, top + size, left + 4 * size,

top + 4 * size);

g.drawString("Voila!", left, top);

}

}

Page 21: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 21 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

(8 marks)

Page 22: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 22 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 9 (13 marks)

Consider the following class which represents a star: public class Star {

private int xPos, yPos;

private int brightness;

public Star() {

xPos = (int)(Math.random() * 700);

yPos = (int)(Math.random() * 400) + 100;

brightness = (int)(Math.random() * 50) + 10;

}

public int getBrightness() {

return brightness;

}

public void drawStar(Graphics g) {

g.fillOval(xPos, yPos, brightness, brightness);

}

}

The JPanel defined below gives us limited power to control the night sky, and contains the following components:

numberT a JTextField which displays the current number of stars in the sky. addB, removeB two JButtons which add and remove stars, respectively.

As well as these components, the JPanel has instance variables stars, storing the array of Star objects currently in the sky, and num, the current number of stars. The constant MAX_STARS stores the maximum number of stars than can exist at once.

Below are two screenshots of the JPanel, one when it first appears and the other after some stars have been added. Initially there are no stars in the sky. Unless there are already MAX_STARS number of stars in the stars array, pressing the "Add Star" button should add one star to the stars array. This causes a new star to be created and drawn on the screen. The "Remove Star" button should remove the most recently added star. The JTextField should always display the current number of stars.

Page 23: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 23 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

You are required to complete the following JPanel definition so that the JPanel behaves as described above. You MUST use the variables given in the code, and make use of the Star class to keep track of the stars and draw them on the screen.

import java.awt.*; import javax.swing.*;

import java.awt.event.* public class AJPanel extends JPanel { public static final int MAX_STARS = 50; private JTextField numberT; private JButton addB, removeB; private int num; private Star[] stars;

public AJPanel() {

num = 0; stars = new Star[MAX_STARS];

numberT = new JTextField(5); numberT.setText("0"); addB = new JButton("Add Star"); removeB = new JButton("Remove Star"); add(new JLabel("Number of Stars:")); add(numberT); add(addB); add(removeB);

addB.addActionListener(this); removeB.addActionListener(this);

}

implements ActionListener

Page 24: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 24 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

public void actionPerformed(ActionEvent e) {

if (e.getSource() == addB && num != MAX_STARS) { stars[num++] = new Star(); } else if (e.getSource() == removeB && num != 0) { num--; } numberT.setText(""+num); repaint();

} public void paintComponent(Graphics g) { super.paintComponent(g);

for (int i = 0; i < num; i++) { stars[i].drawStar(g); }

} }

(13 marks)

Page 25: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 25 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

Question 10 (15 marks)

Complete the following JPanel which uses a Timer object. The Timer object is created with a delay of 50 milliseconds and the Timer starts as soon as the JPanel is created. The JPanel implements a simple game. A ball of size 40 pixels with initial position given by the constant INITIAL_POSITION bounces back and forth horizontally within a square on the screen (with left and right hand edges given by MIN_X and MAX_X, respectively). The edge of the ball should never cross the square. A screenshot of the ball bouncing off the right edge is shown below. The number of pixels the ball moves with each tick of the timer is given by the instance variable speed, which initially is assigned a random value in the reset() method. While the ball is bouncing back and forth, the goal is for the user to click on the ball. If the user clicks on the ball (i.e., inside the ballRect Rectangle), the timer should stop. However, if the user clicks and misses the ball, the ball should move faster by 1 pixel per timer tick. Once the user has ‘won’ (i.e., successfully clicked on the ball) and the timer is stopped, the user should be able to reset the game by pressing the down arrow key. When this key is pressed the ball should be reset to its initial parameters and the timer should start again.

Note: You MUST use the variables and constants given in the code.

import java.awt.*; import javax.swing.*; import java.awt.event.*;

public class AJPanel extends JPanel {

public static final int MAX_SPEED = 10; public static final Rectangle INITIAL_POSITION =

new Rectangle(200, 200, 40, 40); public static final int MIN_X = 10, MAX_X = 500;

private Rectangle ballRect; private int speed; private Timer t;

public AJPanel() {

implements ActionListener, KeyListener, MouseListener

Page 26: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 26 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

reset(); t = new Timer(50, this); addKeyListener(this); addMouseListener(this); t.start();

}

private void reset() { speed = (int)(Math.random() * MAX_SPEED + 1); ballRect = new Rectangle(INITIAL_POSITION); }

public void actionPerformed(ActionEvent e) { ballRect.x += speed; if (ballRect.x + ballRect.width > MAX_X) { ballRect.x = MAX_X - ballRect.width; xSpeed = xSpeed * -1; } if (ballRect.x < MIN_Y) { ballRect.x = 0; xSpeed = xSpeed * -1; } repaint();

}

Page 27: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 27 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

public void paintComponent( Graphics g ) { super.paintComponent( g ); g.drawRect(MIN_X, 10, MAX_X - MIN_X, 300);

g.fillOval(ballRect.x, ballRect.y,

ballRect.width, ballRect.height);

}

public void keyPressed( KeyEvent e ) {

if ( !t.isRunning() && e.getKeyCode() ==

KeyEvent.VK_DOWN ) { reset(); t.start(); } repaint();

}

Page 28: THE UNIVERSITY OF AUCKLAND · THE UNIVERSITY OF AUCKLAND SUMMER SEMESTER, 2013 Campus: City COMPUTER SCIENCE WITH ANSWERS Principles of Programming (Time Allowed: TWO hours) NOTE:

Question/Answer Sheet - Page 28 - CompSci 101

SURNAME: ...................................................... FORENAMES: ...........................................................

public void mousePressed( MouseEvent e ) {

Point pressPt = e.getPoint(); if (ballRect.contains(pressPt)) { t.stop(); } else { if (speed > 0) { speed++; } else { speed--; } }

} public void keyReleased( KeyEvent e ) {} public void keyTyped( KeyEvent e ) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseReleased(MouseEvent e) {}

}

(15 marks)