• Tidak ada hasil yang ditemukan

int answer = 0; for (int i = 1; i <= 6; i++) { for (int j = 0; j < 5; j++) { answer++; } System.out.print(answer marks) f) What is the output of the following code

N/A
N/A
Protected

Academic year: 2023

Membagikan "int answer = 0; for (int i = 1; i <= 6; i++) { for (int j = 0; j < 5; j++) { answer++; } System.out.print(answer marks) f) What is the output of the following code"

Copied!
31
0
0

Teks penuh

(1)

FIRST SEMESTER, 2006 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

(/40) Q4

(/5) Q7

(/7) Q10

(/10) Q2

(/5) Q5

(/10) Q8

(/7) Q3

(/6) Q6

(/6) Q9

(/4)

TOTAL

(/100)

(2)

Question 1 (40 marks)

There are 20 parts to this question, each worth 2 marks. Write your answer in the space provided for each part.

a) What is the output of the following code?

System.out.println(2+2*2);

(2 marks) b) Consider the following code:

int x;

x = ((int)(Math.random()*10)) / 3 + 1;

Write down all of the possible values that x may contain after the assignment statement.

(2 marks)

c) Consider the following code:

int i = 0;

int s = 0;

int n = 10;

while (i < n) { s = s + i;

}

Assuming this code is contained inside a method in a valid class, will it compile without error?

(2 marks)

(3)

d) Is the following code a valid way of creating and initialising an array?

int[] array;

array = {1, 2, 3, 5};

(2 marks)

e) What is the output of the following code?

int answer = 0;

for (int i = 1; i <= 6; i++) { for (int j = 0; j < 5; j++) { answer++;

}

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

}

(2 marks)

f) What is the output of the following code?

int answer = 0;

for (int i = 1; i <= 6; i++) { for (int j = 0; j < i; j++) { answer++;

}

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

}

(2 marks)

(4)

g) In the start() method below, assign a value to the variable number so that the output produced by the start() method will be:

sum: 1

Complete the assignment in the space provided below:

public void start() { int sum = 0;

int number =

(2 marks) if (number > 40) {

sum++;

if(number <= 50) { sum++;

}

sum++;

}

if (number%2 == 1) { sum++;

}

sum++;

if (number > 50 || number <= 0) { sum++;

}

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

}

h) What is stored in array a after the following statements have been executed?

String[] a = {"one", "two", "three", "four"};

String[] b;

b = a;

a[0] = a[1];

b[1] = a[2];

{ " " , " " , " " , " " }

(2 marks)

(5)

i) What is the output of the following code?

String word = "ADDITIONS";

if (! word.equals("")) {

System.out.println("ABC");

if (word.length() > 4 && word.length() < 9) { System.out.println("DEF");

} else {

System.out.println("GHI");

}

} else if (word.charAt(3) == word.charAt(5)) { System.out.println("JKL");

if (word.length() > 4 && word.length() < 9) { System.out.println("DEF");

} else {

System.out.println("GHI");

} }

(2 marks)

j) What is the output of the following code?

public class Program { public void start() {

int result = method1(6, 4);

System.out.println(result);

}

private int method1(int number1, int number2){

int result = number2 / number1;

System.out.println(number2 + "/" + number1);

return result;

} }

(2 marks)

(6)

The next 3 questions relate to the Computer class below.

public class Computer { private int memory;

private int processor;

/**

* Constructs a Computer object.

* @param memory The memory in MB.

* @param processor The speed in GHz.

*/

public Computer(int memory, int processor) { this.memory = memory;

this.processor = processor;

} /**

* @return The memory value.

*/

public int getMemory() { return memory;

} /**

* Sets the memory value.

* @param memory */

public void setMemory(int memory) { this.memory = memory;

} }

k) Complete the code to construct a reference to a Computer object with 1024MB of memory and 2GHz processor speed.

Computer myComputer =

(2 marks) l) Write the code to print the value of the amount of memory stored in the Computer object you

have just constructed in part (k). For example, assuming you have constructed the object correctly in part (k), the output from the code you write below should be: "1024".

(2 marks)

(7)

m) Write the code to add an extra 1024MB of memory to the amount of memory that is currently stored in the myComputer object.

(2 marks) n) What is the output of the following code?

Point[] pts = new Point[2];

pts[0] = new Point(100, 200);

pts[1] = new Point(300, 400);

Point temp = pts[1];

int valueY = pts[0].y;

pts[0].y = 999;

temp.x = valueY;

pts[1] = pts[0];

pts[0] = temp;

System.out.println(pts[0].x + " , " + pts[0].y);

System.out.println(pts[1].x + " , " + pts[1].y);

(2 marks)

o) Given a Rectangle object, r, and a Point object p, complete the code below that tests to determine if the location of the point is anywhere inside the rectangle. If it is, the word

"INSIDE" should be printed, otherwise the word "OUTSIDE" should be printed.

if ( ) { System.out.println("INSIDE");

} else {

System.out.println("OUTSIDE");

}

(2 marks)

(8)

p) Consider the mystery() method defined below:

private boolean mystery(int[] a) {

for (int i = 0; i < a.length-1; i++) { if (a[i] <= a[i+1]) {

return false;

} }

return true;

}

Complete the diagram of the array nums below, by filling it in with integer values such that the method call:

mystery(nums)

would return the value true.

(2 marks)

q) List two kinds of actions (that you have seen this semester) that will cause an event of type ActionEvent to be generated.

(2 marks)

0 1 2 3

nums

(9)

r) What is the output of the following code?

public class Program { public void start() {

System.out.println(method2("APPLES"));

}

private boolean method2(String word) { word = word.toLowerCase();

System.out.println(word);

if (word.indexOf("A") > -1) { return false;

}

return word.length() > 4;

} }

(2 marks) s) What is the output of the following code?

public class Program { public void start() {

String wordMix = method3("HELLO", "WORLD");

System.out.println(wordMix);

}

private String method3(String word1, String word2){

int pos1 = word1.length() - 2;

int pos2 = word2.length() - 3;

System.out.println(word1.substring(0, pos1));

return word2.substring(pos2) + word1.substring(0, pos1);

} }

(2 marks)

(10)

t) The Numbers class is defined as follows:

public class Numbers {

private static int value = 0;

private int number;

public Numbers(int num) { value = value + num;

number = num;

}

public String toString() {

return "number: " + number + " value: " + value;

} }

What is the output of the following code?

public class Program { public void start() {

Numbers num1 = new Numbers(3);

Numbers num2 = new Numbers(5);

System.out.println(num1.toString());

} }

(2 marks)

(11)

Question 2 (5 marks)

Complete the diagonal() method to print out a diagonal line of 'x's. The parameter is the number of 'x's and the number of lines to print. The first 'x' is next to the margin; each following 'x' is one further space to the right. For example, the call diagonal(10) would produce the following output.

x x x x x x x x x x

Complete the diagonal() method below:

private void diagonal(int number) {

}

(5 marks)

(12)

Question 3 (6 marks)

Complete the source code for the following MyJPanel class so that the program performs exactly as described below.

When the window first appears, a rectangular border is drawn near the edges of the window. In addition, a filled-in circle is drawn so that it just touches the top edge of this rectangular border. The horizontal position of this circle is centred exactly in the middle of the rectangular border.

The screenshot on the right shows what the window should look like when it first appears.

When the mouse button is pressed anywhere inside the window, this circle should start moving down the screen as though it were falling.

For example, the screenshot on the left below shows the program shortly after the mouse button has been pressed.

The circle should continue to fall down the screen until it reaches the bottom edge of the rectangular boundary, at which point it must stop as shown on the right below.

Notice, the paintComponent() method has been provided to you. You need to complete the constructor method, the actionPerformed() method and the mousePressed() method.

Notes:

• The y position of the circle should change by 5 pixels each time it moves.

• The Timer should have a delay of 50 milliseconds.

• Once it has started falling, it should only stop moving once there is no gap between the bottom edge of the border and the bottom edge of the circle.

• The addMouseListener(this) statement has already been added for you in the constructor method.

(13)

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class MyJPanel extends JPanel implements

ActionListener, MouseListener { private Timer t;

private Point pos;

public MyJPanel() {

addMouseListener(this);

} (2 marks)

public void mousePressed(MouseEvent e) {

} (1 mark)

public void actionPerformed(ActionEvent e) {

} (3 marks)

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

g.fillOval(pos.x-25, pos.y-25, 50, 50);

g.drawRect(50, 50, 300, 300);

}

public void mouseReleased(MouseEvent e) {}

public void mouseClicked(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

}

(14)

Question 4 (5 marks)

Complete the swapPairs() method so that it swaps adjacent pairs of elements. For example, the array:

{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } gets turned into

{ 2, 1, 4, 3, 6, 5, 8, 7, 10, 9 }.

If the array has an odd number of elements the last element does not move. For example, the array:

{ 4, 2, 7 } gets turned into

{ 2, 4, 7 }.

Complete the swapPairs() method below:

private void swapPairs(int[] array) {

}

(5 marks)

(15)

Question 5 (10 marks)

The GrowingArray class contains an array and a size. The size indicates the number of elements currently stored in the array.

public class GrowingArray { private int size;

private int[] data;

public GrowingArray() { data = new int[4];

size = 0;

}

public String toString() { ...

}

public int elementAt(int position) { ...

}

public void addElement(int number) { ...

} }

a) Complete the toString() method so that when it is called, the first 'size' elements currently stored in the array are returned in a String, separated by commas. For example, if the array currently holds {3, 6, 9, 0} and the value of size is 3 the returned String must be:

"3, 6, 9"

N.B. The toString() method does not print the elements to the screen.

public String toString() {

(16)

} (4 marks) b) Complete the elementAt() method which returns the element of the data array at the

position specified by the parameter. You do not have to consider invalid values for position.

public int elementAt(int position) {

} (1

mark)

c) Adding an element to a GrowingArray object is done with the addElement() method.

Normally this requires the element to be stored in the next available position of the data array, and then the size value to be updated. However when the GrowingArray object is already full, extra space must be made for the data.

In this case, the addElement() method constructs a new array twice the size of the current array and copies all the elements to the new array. This new array then becomes the data array for the object.

Complete the addElement() method below.

public void addElement(int number) {

(17)

} (5 marks)

(18)

Question 6 (6 marks)

Draw the output produced by the following code, in the grid given at the bottom of this page.

The grid lines are not part of the output but are there to help you place the drawing in the correct position. Each square in the grid is 10 pixels by 10 pixels.

import java.awt.*;

import javax.swing.*;

public class DrawJPanel extends JPanel {

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

draw(g, 30, 20, 10);

}

private void draw(Graphics g, int x, int y, int size) { g.fillRect(x, y, size, size*2);

g.fillRect(x+size*5, y, size, size*2);

g.fillOval(x+size*2, y, size*2, size*2);

g.drawLine(x+size*7, y+size, x+size*8, y+size*2);

g.drawLine(x+size*8, y+size*2, x+size*11, y);

g.drawString("Great", x+size*6, y);

} }

(19)

(6 marks) Question 7 (7 marks)

Complete the method, printSameInitialChar(), which accepts two parameters: an array of Strings and a char. The method should print all the words in the String array which start with the same character as the character passed as a parameter.

Note: You can assume that each element of the String array passed to the method is a valid String object and contains at least one character.

For example, executing the Q7 application with the completed printSameInitialChar() method produces the following output:

> java Q7

Start with the letter c chicken

cats

Start with the letter a Start with the letter d dogs

deers

Start with the letter m mice

10 20 30 40 50 60 70 80 90 100 110 120 130 140 0

10 20 30 40 50 60 70 80 90 100

120

140 110

130

(20)

public class Q7 {

public void start() {

String[] words = { "chicken", "kittens", "cats", "dogs",

"bats", "goats", "rats", "mice", "deers" };

System.out.println("Start with the letter c ");

printSameInitialChar(words, 'c');

System.out.println();

System.out.println("Start with the letter a");

printSameInitialChar(words, 'a');

System.out.println();

System.out.println("Start with the letter d");

printSameInitialChar(words, 'd');

System.out.println();

System.out.println("Start with the letter m");

printSameInitialChar(words, 'm');

}

(21)

private printSameInitialChar(

){

}

} (7 marks)

(22)

Question 8 (7 marks)

Complete the method, mixUpWords(), which accepts a String parameter and returns a String. The method should generate a random position in the parameter String. This random position splits the parameter String into two parts (one of these parts may be the empty String). The method returns a String made up of the second part of the parameter String followed by the first part of the parameter String.

Note: You can assume that the String passed to the method always contains at least one character.

For example, executing the Q8 application with the completed mixUpWords() method produces the following output:

> java Q8 1. RDSWO 2. DSWOR 3. A

4. ORDS TO MIXW 5. ticfantas

public class Q8 {

public void start() {

System.out.println("1. " + mixUpWords("WORDS"));

System.out.println("2. " + mixUpWords("WORDS"));

System.out.println("3. " + mixUpWords("A"));

System.out.println("4. " + mixUpWords("WORDS TO MIX"));

System.out.println("5. " + mixUpWords("fantastic"));

}

private mixUpWords( ){

(23)

}

} (7 marks)

Question 9 (4 marks)

The following method, distance(), is supposed to take an array of Point objects as a parameter, and return the horizontal distance between the leftmost and the rightmost point in that array.

public int distance(Point[] pts) { int left = pts[0].x;

int right = left;

for (int i = 1; i < pts.length; i++) { if (pts[i].x > right) {

right = pts[i].x;

} else {

left = pts[i].x;

} }

return right - left;

}

If the distance() method is defined correctly, the following code:

Point[] pts = new Point[3];

pts[0] = new Point(100, 200);

pts[1] = new Point(301, 400);

pts[2] = new Point(300, 600);

System.out.println(distance(pts));

should produce the output:

201

as that is the horizontal distance between the leftmost and rightmost points.

However, there is a serious logic error in the distance() method as it is defined above, and the output "1" is produced when the previous code segment is executed. This error can be corrected by modifying a single line of code.

In the source code listing above, circle the code causing the logic error. Then, in the space provided below, give a correction for the logic error. You only need to write the line of code that you have changed.

(24)

(4 marks) Question 10 (10 marks)

A simple game consists of a square moving around the screen which the user must control so that it does not collide with any of a collection of randomly sized and positioned obstacles,

displayed as rectangles.

The moving square is represented by the Square class defined below:

import java.awt.*;

public class Square {

private Point pos; // the center of the square private int direction; // the direction of the square private final int LEFT = 0;

private final int RIGHT = 1;

private final int UP = 2;

private final int DOWN = 3;

private final int DISTANCE_TO_MOVE = 5;

public Square(int x, int y) { pos = new Point(x, y);

direction = LEFT;

}

// This method returns the current position of the square // as a Rectangle object

public Rectangle getRect() {

return new Rectangle(pos.x-10, pos.y-10, 20, 20);

}

public void draw(Graphics g) {

g.fillRect(pos.x-10, pos.y-10, 20, 20);

}

public void move() {

if (direction == LEFT)

pos.x -= DISTANCE_TO_MOVE;

else if (direction == RIGHT)

(25)

pos.x += DISTANCE_TO_MOVE;

else if (direction == UP)

pos.y -= DISTANCE_TO_MOVE;

else

pos.y += DISTANCE_TO_MOVE;

}

public void setDirection(int newDirection) { direction = newDirection;

} }

(26)

The collection of obstacles is represented by the Obstacles class defined below:

import java.awt.*;

public class Obstacles {

private Rectangle[] rects;

public Obstacles(int howMany) {

rects = new Rectangle[howMany];

for (int i = 0; i < rects.length; i++) { int x = (int)(Math.random()*500);

int y = (int)(Math.random()*500);

int w = (int)(Math.random()*200);

int h = (int)(Math.random()*200);

rects[i] = new Rectangle( x, y, w, h);

} }

public boolean collides(Square s) { ...

...

}

public void draw(Graphics g) {

for (int i = 0; i < rects.length; i++) { g.drawRect(rects[i].x, rects[i].y,

rects[i].width, rects[i].height);

} }

}

Notice the collides() method has not been completed.

In the JPanel class, the actionPerformed() method updates the position of the Square object, and stops the timer (an object of type Timer) which controls the animation if the Square collides with any of the obstacles. The actionPerformed() method is defined as follows:

public void actionPerformed(ActionEvent e) { square.move();

if (obstacles.collides(square)) { timer.stop();

}

repaint();

}

Note: the Square class contains a getRect() method which you may find useful.

(27)

For this question you need to define the collides() method in the Obstacles class.

public boolean collides(Square s) {

(10 marks) }

(28)

OVERFLOW PAGE

(If you have used this page, please indicate clearly under the relevant question that you have overflowed to this page)

(29)

OVERFLOW PAGE

(If you have used this page, please indicate clearly under the relevant question that you have overflowed to this page)

(30)

ROUGH WORKING (WILL NOT BE MARKED) (You may use this page for rough working)

(31)

ROUGH WORKING (WILL NOT BE MARKED) (You may use this page for rough working)

Referensi

Dokumen terkait

As you do not have a record for this item in your company file, the Select from List window appears.. 11 You need to create the

[r]