• Tidak ada hasil yang ditemukan

System.out.println mark) d) What is printed when the following statement is executed

N/A
N/A
Protected

Academic year: 2023

Membagikan "System.out.println mark) d) What is printed when the following statement is executed"

Copied!
24
0
0

Teks penuh

(1)

THE UNIVERSITY OF AUCKLAND

First Semester, 2003 City Campus

COMPUTER SCIENCE Principles of Programming

(Time allowed: TWO HOURS)

Surname:

Forenames:

Student ID number:

Login name (UPI):

INSTRUCTIONS:

• Attempt ALL questions - write your answers in the box provided

• Calculators are NOT permitted

Examiner to complete:

Question Mark Question Mark

1 (/15) 6 (/10)

2 (/10) 7 (/10)

3 (/5) 8 (/10)

4 (/15) 9 (/10)

5 (/5) 10 (/10)

TOTAL: (/100)

(2)

Question 1 (15 marks)

a) What type of variable should be used to hold the value listed below?

56.0

(1 mark) b) What type of variable should be used to hold the value listed below?

'F'

(1 mark) c) What is printed when the following statement is executed?

System.out.println( 7%5 );

(1 mark) d) What is printed when the following statement is executed?

System.out.println( 12%13 );

(1 mark) e) What is printed when the following statements are executed?

int a = 3, b = 4;

System.out.println( ++a + " " + b++ );

(1 mark)

(3)

f) What is printed when the following statement is executed?

System.out.println( 1+2*3/4 );

(1 mark) g) What is printed when the following statement is executed?

System.out.println( 4/3*(2+1) );

(1 mark) h) What is printed when the following statement is executed?

System.out.println( (double)1+2/3 );

(1 mark) i) What is printed when the following statement is executed?

System.out.println( 3/4*1.0 + 1.0*3/4 );

(1 mark) j) What is printed when the following statement is executed?

System.out.println( 1 + 2 + "3" + 4 + 5 );

(1 mark)

(4)

k) What is printed when the following statements are executed?

int a = 4;

int b = 5;

a = b;

b = a;

System.out.println( a + " " + b );

(1 mark) l) What is printed when the following statement is executed?

System.out.println( "1" + "//\\+" + "+//\\" + 2 );

(1 mark) m) What is printed when the following statements are executed?

String s = "Hello";

String w = s.substring(2,3);

System.out.println( s + " " +w );

(1 mark) n) What is printed when the following statements are executed?

int a = 3;

int b = 4;

int c = 5;

System.out.println( Math.max(a, Math.min(Math.max(a,c), b)) );

(1 mark) o) What is printed when the following statement is executed?

System.out.println( (int)4.8/(double)2 );

(1 mark)

(5)

Question 2 (10 marks)

For this question, you need to write a method called printTotal() which takes an array of Strings as a parameter, where each String in the array represents an integer value. The method should then calculate the sum of the values in the array and print the result to the screen using System.out.println().

The array containing the Strings may contain null values. For example, the following code:

String[] nums = new String[8];

nums[1] = "23";

nums[3] = "6";

nums[7] = "14";

would create the array of Strings below:

If this array was passed to the printTotal() method, the output would be:

43

Complete the printTotal() method below. You can assume the Strings in the array represent valid numbers, hence you do not need to worry about try/catch or handling any exceptions:

private static void printTotal(String[] numbers) {

}

(10 marks)

0 1 2 3 4 5 6 7

nums

"23" "6" "14"

(6)

Question 3 (5 marks)

Read the code below and answer part (a) and part (b)

int a = 20, b = 15, c = 5;

if( b < a && (a > c || c < b)) if( b > a - c )

if( c < b ) b = c - a;

else a = 10;

else if( a - c == b) b = a;

else b = c;

if( a > b || a - c < b ) if( b == a && c < b ) if( c > b || a - b > c) c = a;

else a = c;

else c = b*2;

else a = b*2;

System.out.println(a + " " + b + " " + c );

a) Rewrite the code given above using correct indentation. Guidelines have been given to show the position of the each tab.

(7)

(2 marks) b) What is the output of the code listed above?

(3 marks)

(8)

Question 4 (15 marks)

a) Complete the toLowerCaseNoSpaces() method below. The toLowerCaseNoSpaces() method should return a String the same as the original String passed as a parameter but with all the spaces removed and all characters in lower case.

For example:

System.out.println(toLowerCaseNoSpaces("What a load of

RUBBISH."));

would print

whataloadofrubbish.

Complete the code for this method below:

private static String toLowerCaseNoSpaces(String s) {

}

(5 marks)

b) Complete the reverseString() method. The reverseString() method returns a String that is the reverse of the String passed as a parameter.

For example:

System.out.println(reverseString("backwards and forwards"));

would print

sdrawrof dna sdrawkcab

(9)

Complete the code for this method below:

private static String reverseString(String s) {

}

(5 marks) c) A palindrome is a string that is the same forwards as backwards (ignoring spaces and the case of letters). Complete the printPalindromes() method which checks to see if a String is a palindrome and prints an appropriate message. For example, the output from these statements:

printPalindrome("Able was I ere I saw Elba");

printPalindrome("I think therefore I am");

printPalindrome("A man a plan a canal Panama");

should be:

"Able was I ere I saw Elba" is a palindrome.

"I think therefore I am" is not a palindrome.

"A man a plan a canal Panama" is a palindrome.

You must use the toLowerCaseNoSpaces() and reverseString() methods in the printPalindrome() method.

private static void printPalindrome(String s) {

}

(5 marks)

(10)

Question 5 (5 marks)

What is the output of the following program? You may find it useful to use the desk-checking technique covered in lectures. The space on the facing page can be used to show the diagram you used to desk-check the code (below).

public class Q5 {

public static void main(String[] args) { int a = 1, b = 2, c = 3;

c = method02(b);

a = method01(a);

b = method02(c, 4);

System.out.println(a + " " + b + " " + c);

}

private static int method02(int b) {

b = 6;

return b+b;

}

private static int method02(int b, int c) { System.out.println(b + " " + c);

return b - c;

}

private static int method01(int a) { a = 4;

int b = 5;

int c = method02(b, a);

return c;

} }

Show the output here:

C:/> java Q5

(5 marks)

(11)

This space may be used for working (there are no marks allocated for showing your working):

(12)

Question 6 (10 marks)

Carefully examine the following definition of the Person class, which stores the name, height and age of a particular person:

public class Person {

private String name;

private int height;

private int age;

public Person(String n, int h, int a) {

name = n;

height = h;

age = a;

}

public void birthday() { age++;

}

public void swapHeight(Person other) { int temp = other.height;

other.height = height;

height = temp;

System.out.println("Swapping heights of "

+ other.name + " and " + name);

}

public void print() {

System.out.println(name + " - " + height + " - "

+ age);

} }

You need to complete the source code for the Q6 class below, which creates and calls methods on two Person objects, so that the output produced is exactly the same as that shown below:

C:/> java Q6 Joe - 190 - 18 Susan - 170 - 60

Swapping heights of Joe and Susan Joe - 170 - 21

Susan - 190 - 60

Note: the age of Joe has changed from 18 to 21.

You must not use any System.out.print() or System.out.println() statements in the Q6 class below. You should produce the required output simply by calling methods on the two Person objects you create.

(13)

public class Q6 {

public static void main(String[] args) {

Person a;

Person b;

(10 marks) }

}

(14)

Question 7 (10 marks)

For this question you need to complete the code for a Frame class which allows the user to draw horizontal lines, inside a box drawn on the screen, by pressing the mouse button. The screenshot on the left below shows the Frame when it is first created. Notice there is the outline of a box drawn in the window. If the user presses the mouse button outside of the box, nothing happens, as shown in the screenshot below on the right:

However, when the user presses the mouse button inside the box, a horizontal line will be drawn at the y-position of the mouse press from one edge of the box to the other. The screenshot on the left below shows the mouse being pressed inside the box for the first time. The maximum number of lines that can be drawn inside the box is 10. The screenshot on the right below shows the window just after the mouse has been pressed and the 10th line has been drawn.

Once the maximum number of lines have been drawn, nothing further will be drawn when the mouse is pressed, as shown in the screenshot on the right.

Complete the source code for the Q7Frame class below.

Several variables have been declared for you:

• the variable box has been declared and initialised for you – this variable stores the position of the box drawn on the screen.

• the variable yVals is an array of ints and should be used to store the positions of the lines.

• the variable numLines should be used to store the number of lines stored in the array yVals.

(15)

import java.awt.event.*;

public class Q7Frame extends Frame implements MouseListener {

private Rectangle box;

private int[] yVals;

private int numLines;

public Q7Frame(String title, int x, int y, int width,

int height) { box = new Rectangle(50, 50, 100, 100);

yVals = new int[10];

numLines = 0;

addMouseListener(this);

// DON'T CHANGE CODE BELOW THIS LINE // removed for clarity

// DON'T CHANGE CODE ABOVE }

public void paint(Graphics g) {

} (4 marks)

public void mousePressed(MouseEvent e) {

} (6 marks)

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mouseClicked(MouseEvent e) {}

}

(16)

Question 8 (10 marks)

Complete the diagonalAdd() method to add up the bottom-left to top-right diagonal of a 2 dimensional array of positive integers.

For example, if the diagonalAdd() method is called by the main() method below the answer is 7 + 5 + 3 = 15.

public static void main(String[] args) {

int[][] a = { {1, 2, 3 },

{4, 5, 6 },

{7, 8, 0 }

};

int answer = addDiagonal(a);

}

If the number of rows is different from the number of columns the method should return -1. You may assume that every row in an array has the same number of elements.

private static int addDiagonal(int[][] numbers) {

}

(10 marks)

(17)

Question 9 (10 marks)

Here is a small Time class. It contains a plus() method to add two Time objects together. In order to automatically test whether the plus() method is correct you must complete the

equals() method and then write a main() method to check the plus() method by adding two Times together and checking to see if the result is correct.

/**

* A simple class to hold the components of a time.

*/

public class Time {

/** The hour 0 - 23. */

private int hour;

/** The minute 0 - 59. */

private int minute;

/** The second 0 - 59. */

private int second;

/**

* Constructs a Time object.

* @param hour the hour of the time * @param minute the minute of the time * @param second the second of the time

*/

public Time(int hour, int minute, int second) { this.hour = Math.abs(hour) % 24;

this.minute = Math.abs(minute) % 60;

this.second = Math.abs(second) % 60;

}

/**

* Adds two times together.

* @param otherTime the other time

* @return the sum of this time with the otherTime

*/

public Time plus(Time otherTime) {

Time result = new Time(hour + otherTime.hour, minute + otherTime.minute, second + otherTime.second);

if (result.second >= 60) { result.minute++;

result.second -= 60;

}

if (result.minute >= 60) { result.hour++;

result.minute -= 60;

}

if (result.hour >= 24)

result.hour -= 24;

return result;

}

(18)

/**

* Indicates whether some other Time object is "equal to" this Time.

* @param other the other Time object to compare

* @return true if other is equal to this Time; else false

*/

public boolean equals(Time other) { ...

} }

a) Complete the equals() method for the Time class:

public boolean equals(Time other) {

}

(3 marks) b) Write down two Times in the form HH:MM:SS (e.g. 22:15:45) and write the answer you would expect (if the Time class worked correctly) from adding the two Times together using the plus() method. The answer should also be written in HH:MM:SS form.

Time 1:

Time 2:

Correct sum:

(2 marks)

(19)

c) Write a main() method that could be used to automatically test the plus() method of the Time class by adding together the two Times you wrote down in (b) and using the equals() method you wrote in (c) to check if the result is the same as the correct sum that you also wrote down in (b).

The main() method you write below should either print the word "success" if the addition was correct or the word "failure" if the addition was wrong.

public static void main(String[] args) {

}

(5 marks)

(20)

Question 10 (10 marks)

Complete the printPyramid() method to produce a triangle of empty spaces surrounded by

"+"s. If the parameter is 4 the method should produce:

+++++++++

++++ ++++

+++ +++

++ ++

+ + +++++++++

If the parameter is 1 the method should produce:

+++

+ +

+++

Your method should work for any positive integer value. You may use helper methods to structure your solution.

private static void printPyramid(int rows) {

(21)

(10 marks)

(22)

OVERFLOW PAGE

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

(23)

OVERFLOW PAGE

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

(24)

APPENDIX:

Useful methods and variables:

String

public int indexOf(char c)

public int indexOf(String string) public char charAt(int index)

public String substring(int beginIndex, int endIndex) public int length()

public boolean equals(String comparison) public String toLowerCase()

public String toUpperCase()

StringTokenizer

public boolean hasMoreTokens() public String nextToken()

Math

public static double random()

Character

public static char toLowerCase(char ch) public static char toUpperCase(char ch)

Referensi

Dokumen terkait

We do not have a variable which will be used to push the time derivative of descent function (25) less than zero.. The similar method using artificial input can be seen in [8]..

The method used to build the model is a time delay model by considering the vaccination factor as a model parameter, model analysis using the next generation matrix method to