CompSci 101 with answers THE UNIVERSITY OF AUCKLAND FIRST SEMESTER, 2012 Campus: City COMPUTER SCIENCE 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 Q4 Q7 Q10 Q2 (/12) Q5 (/15) Q8 (/6) Q11 (/6) Q3 (/10) Q6 (/4) Q9 (/10) Q12 (/7) (/8) (/6) (/6) TOTAL (/10) (/100)
Question/Answer Sheet - 2 - CompSci 101 with answers Question 1 (12 marks) a) Complete the output produced when the following code is executed. int x = 7 + 3 * 6 / 2-1; int y = 2 % 2 + 2 * 2-2 / 2; System.out.println("x = " + x); System.out.println("y = " + y); x = 15 y = 3 (2 marks) b) The following section of code does not compile. Identify the error by circling the error and writing out the corrected single line of code. The output of the corrected code is "Woman". int gender = 1; if ( gender = 1) { System.out.println("Woman"); else { System.out.println("Man"); if ( gender == 1) { (2 marks) c) The following section of code does not execute as it should. Identify the problem and correct the code. The output of the corrected code should be "6" (i.e. the sum of 0, 1, 2 and 3). int z = 0; int sum = 0; while ( z <= 3 ) { sum = sum + z; z++; System.out.println(sum); (2 marks)
Question/Answer Sheet - 3 - CompSci 101 with answers d) Rewrite the following code with correct indentation. String s = "*"; if ( y == 8 ) { if ( x == 5 ) { s = "@@@"; else { s = "###"; s = s + "S"; System.out.println("s: " + s); String s = "*"; if ( y == 8 ) { if ( x == 5 ) { s = "@@@"; else { s = "###"; s = s + "S"; System.out.println("s: " + s); (3 marks) e) Using the code from part d) above, complete the output if x has the value 5, and y has the value 8. s: @@@S (2 marks) f) Using the code from part d) above, complete the output if x has the value 5, and y has the value 7. s: * (1 mark)
Question/Answer Sheet - 4 - CompSci 101 with answers Question 2 (10 marks) a) Complete the getaverage() method which takes two int parameters, x and y, and returns the average of the two parameter values. The return type of the method is a double. For example, the following code: System.out.println("Average of 2 and 3 is " + getaverage(2,3)); System.out.println("Average of 4 and 3 is " + getaverage(4,3)); System.out.println("Average of 4 and 6 is " + getaverage(4,6)); produces the output: Average of 2 and 3 is 2.5 Average of 4 and 3 is 3.5 Average of 4 and 6 is 5.0 private double getaverage(int x, int y) { return (x + y ) / 2.0; b) Complete the printrowofstars() method which is passed an int parameter, n. The method prints n number of stars. For example, the code: printrowofstars(4); (3 marks) produces the following output: **** private void printrowofstars(int n) { for (int i = 0; i < n; i++) { System.out.print("*"); (3 marks)
Question/Answer Sheet - 5 - CompSci 101 with answers c) Complete the printsquareofstars() method which is passed an int parameter, size. The method displays a square of stars. The number of rows is given by the parameter, size, and there are size number of stars in each row. Your answer MUST call the printrowofstars() method defined in part b) above. For example, the following code: printsquareofstars(3); produces the following output: *** *** *** private void printsquareofstars(int size) { for (int i = 0; i < size; i++) { printrowofstars (size); System.out.println(); (4 marks)
Question/Answer Sheet - 6 - CompSci 101 with answers Question 3 (8 marks) a) Given the following method: private void method1(int x, int y, int[] z) { x++; y = 10; if ( z.length >= 1 ) { z[0] = 100; complete the output produced when the following code is executed. int a = 1; int[] b = { 1, 2, 3 ; int[] c = { 1, 2, 3 ; method1(a, b[0], c); System.out.println("a = " + a); System.out.println("b[0] = " + b[0]); System.out.println("c[0] = " + c[0]); a = 1 b[0] = 1 c[0] = 100 (3 marks)
Question/Answer Sheet - 7 - CompSci 101 with answers b) Given the following method: private void method2(point p, Point q, Point r) { p.x = 100; q = new Point(200, 300); r = new Point(300, 400); complete the output produced when the following code is executed. Point d = new Point(1, 2); Point e = new Point(3, 4); Point[] f = { new Point(1, 2), new Point(3, 4) ; method2(d, e, f[0]); System.out.println("d.x = " + d.x); System.out.println("e.x = " + e.x); System.out.println("f[0].x = " + f[0].x); d.x = 100 e.x = 3 f[0].x = 1 c) Given the following method: private void method3(point[] x, Point[] y) { if ( x.length >= 1) { x[0].x = 100; (3 marks) y = new Point[1]; y[0] = new Point(200, 300); complete the output produced when the following code is executed. Point[] g = { new Point(1, 2), new Point(3, 4) ; Point[] h = { new Point(1, 2), new Point(3, 4) ; method3(g, h); System.out.println("g[0].x = " + g[0].x); System.out.println("h[0].x = " + h[0].x); g[0].x = 100 h[0].x = 1 (2 marks)
Question/Answer Sheet - 8 - CompSci 101 with answers Question 4 (15 marks) The class SaleItem represents an item on sale in a shop and is partially defined as follows: public class SaleItem { private String code; private String description; private int price;... a) Complete the following constructor method of the class, which allows the creation of new SaleItem objects. public SaleItem (String code, String desc, int price) { this.code = code; description = desc; this.price = price; (3 marks) b) Complete the following accessor (get) method of the class, which returns the value of the instance variable price. public int getprice() { return price; (3 marks) c) Complete the following mutator (set) method of the class, which sets the value of the instance variable description. public void setdescription(string desc) { description = desc; (3 marks)
Question/Answer Sheet - 9 - CompSci 101 with answers d) Complete the following equals method of the class, which compares the values of two SaleItem objects based on the description and price. public boolean equals(saleitem other) { return description.equals(other. description) && price == other.price; (3 marks) e) Complete the following tostring method of the class, which returns a String representation of the SaleItem object. For example, the following code: SaleItem item = new SaleItem("b123", "Chocolate Biscuits 200g",2); System.out.println(item.toString()); prints: Code-b123,Item-Chocolate Biscuits 200g,Price-$2 public String tostring() { return "Code-" + code + ", Item-" + description + ", Price-$" + price; (3 marks)
Question/Answer Sheet - 10 - CompSci 101 with answers Question 5 (4 marks) Write a code segment that declares and creates an array of integer values with size 100. Use a loop structure to set the value of each element in the array as the square of the corresponding index. For example: the element at position 0 has the value 0, the element at position 1 has the value 1, the element at position 2 has the value 4, the element at position 3 has the value 9, etc. int[] elements = new int[100]; for (int i = 0; i < elements.length; i++) { elements[i] = i * i; Question 6 (6 marks) (4 marks) Give the complete definition of the following copyarray method, which returns a duplicate of the array passed in as a parameter. private int[] copyarray(int[] a) { int[] b; b = new int[a.length]; for (int i = 0; i < a.length; i++) { b[i] = a[i]; return b; (6 marks)
Question/Answer Sheet - 11 - CompSci 101 with answers Question 7 (6 marks) The Stock class represents all the items on sale in a shop. A partial definition of the Stock class is: public class Stock { public static final int MAX_SIZE = 1000; private SaleItem[] items; private int size;... where the items variable is an array of SaleItem objects (from Question 4), and the size variable represents the actual number of items in the array. Give the complete definition of the following findcheapest method in the Stock class, which returns the cheapest item (i.e. the item with the lowest price) in the array. Note: you can assume that the value of size is greater than 0. public SaleItem findcheapest() { SaleItem cheapest; cheapest = items[0]; int pricecheapest = cheapest.getprice(); for (int i = 1; i < size; i++) { if (items[i].getprice() < pricecheapest) { cheapest = items[i]; pricecheapest = cheapest.getprice(); return cheapest; (6 marks)
Question/Answer Sheet - 12 - CompSci 101 with answers Question 8 (10 marks) a) Below is the definition of the array, positions. Note that only some of the elements of the positions array are shown here. Point[] positions = {new Point(70, 10), new Point(90, 30), new Point(50, 30),... ; Write a Java statement which declares a variable p and assigns the LAST element of the positions array to the variable. Point p = positions[positions.length 1]; (2 marks) b) Write a boolean expression which tests whether the Point, p, is inside the Rectangle, r. r.contains(p) (2 marks) c) Write the Java code which swaps the x and the y values of the Point, p. You can assume that the Point, p, has been correctly created. public void start() { Point p =... ; int temp; //x, y values of the Point, p, are not shown temp = p.x; p.x = p.y; p.y = temp; (2 marks)
Question/Answer Sheet - 13 - CompSci 101 with answers d) Below is a diagram showing a Rectangle, r, and a Point, p. The Point, p, is exactly halfway down the left hand side of the Rectangle, r. Complete the Java statement which creates the Point, p, in the correct position. You can assume that the Rectangle, r, has been correctly created. //x, y, width and height of the Rectangle, r, //are not shown Rectangle r =... ; Point p = new Point(r.x, r.y + r.height / 2); (2 marks) e) Below is a diagram showing a Rectangle, r, and a Point. The Rectangle, r, is a square of size 20. The Point, p, has an x value of 50 and a y value of 60 and is the centre of the square. Complete the Java code which creates the Rectangle, r. Point p = new Point( 50, 60 ); Rectangle r = new Rectangle(40, 50, 20, 20); (2 marks)
Question/Answer Sheet - 14 - CompSci 101 with answers Question 9 (6 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); drawpattern(g, 70, 60, 20); private void drawpattern(graphics g, int x, int y, int size) { g.fillrect(x, y, size * 3, size); x = x + size / 2; y = y - size * 2; g.drawoval(x, y, size * 2, size * 2); x = x + size / 2; y = y + size * 3; g.drawline(x, y, x, y + size); x = x + size; g.drawline(x, y, x, y + size); y = y + size; g.drawstring("bau!", x, y);
Question/Answer Sheet - 15 - CompSci 101 with answers (6 marks)
Question/Answer Sheet - 16 - CompSci 101 with answers Question 10 (6 marks) The JPanel defined below contains the following components: nightst pricet priceb discountpriceb A JLabel displaying the String "Number of nights", a JTextField in which the user enters the number of nights, a JLabel displaying the String "Price $", a JTextField which displays the price, a JButton displaying the String "PRICE", a JButton displaying the String "PRICE WITH DISCOUNT". Initially, when the JPanel first appears, the JTextFields are both empty. When the user enters a whole number in the nightst textfield and presses the "PRICE" button, the price is displayed in the pricet textfield. The price for each night is $100. When the user enters a whole number in the nightst textfield and presses the "PRICE WITH DISCOUNT" button, the discounted price is displayed in the pricet textfield. The discount price for each night is $90. You are required to complete the following JPanel definition so that the JPanel behaves as described above. The left-hand screenshot below shows the JPanel after the user has entered the value 3 in the nightst and has pressed the "PRICE" button. The right-hand screenshot below shows the JPanel after the user has entered the value 5 in the nightst and has pressed the "PRICE WITH DISCOUNT" button. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AJPanel extends JPanel implements ActionListener { private JTextField nightst, pricet; private JButton priceb, discountpriceb;
Question/Answer Sheet - 17 - CompSci 101 with answers public AJPanel() { nightst = new JTextField(4); pricet = new JTextField(7); priceb = new JButton("PRICE"); discountpriceb = new JButton("PRICE WITH DISCOUNT"); add(new JLabel(new JLabel("Number of nights")); add(nightst); add(new JLabel("Price $")); add(pricet); add(priceb); add(discountpriceb); priceb.addactionlistener(this); discountpriceb.addactionlistener(this); public void actionperformed( ActionEvent e ) { int numberofnights; int price; numberofnights = Integer.parseInt( nightst.gettext()); if(e.getsource() == priceb) { price = 100 * numberofnights; else { price = 90 * numberofnights; pricet.settext("" + price); (6 marks)
Question/Answer Sheet - 18 - CompSci 101 with answers Question 11 (7 marks) The following JPanel responds to MouseEvents. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class AJPanel implements MouseListener { private final int GAP = 10; private final int CENTRE_X = 100; private int left; private int right; public AJPanel() { addmouselistener(this); left = CENTRE_X; right = CENTRE_X; public void mousepressed(mouseevent e) { int x = e.getx(); int y = e.gety(); if (x > right) { right = right + GAP; else if (x < left) { left = left - GAP; else { if (left < CENTRE_X) { left = left + GAP; if (right > CENTRE_X) { right = right - GAP; repaint(); public void paintcomponent(graphics g) { super.paintcomponent(g); g.fillrect(centre_x - 1, 0, 3, 310); int posx = left; int posy = 20; while(posx < right) { g.drawoval(posx, posy, GAP, 30); posx = posx + GAP; public void mouseclicked(mouseevent e) { public void mouseentered(mouseevent e) { public void mouseexited(mouseevent e) { public void mousereleased(mouseevent e) {
Question/Answer Sheet - 19 - CompSci 101 with answers Note: the grid lines have been drawn in the window to help you. Initially, the JPanel displays a vertical filled rectangle of width 3 pixels (see the JPanel on the right). Show the JPanel after the user has pressed the mouse two times: first mouse press occurs at position 30, 90 second mouse press occurs at position 140, 10 Show the JPanel after the user has pressed the mouse one more time: third mouse press occurs at position 20, 40 Now show the JPanel after the user has pressed the mouse another time: fourth mouse press occurs at position 95, 40 (7 marks)
Question/Answer Sheet - 20 - CompSci 101 with answers Question 12 (10 marks) You are required to complete the following JPanel which uses a Timer object. The Timer object is created with a delay of 300 milliseconds and the Timer starts as soon as the JPanel is created. The JPanel displays twelve squares in a formation similar to a clockface. The top left position of each square is stored in the Point array, POSITIONS, i.e., the top left position of the top square (12 noon) is stored in POSITIONS[0], the top left position of the second square (1pm) is stored in POSITIONS[1], the top left position of the third square (2pm) is stored in POSITIONS[2], etc. Initially, when the JPanel first appears, the top square (12 noon) is filled with red. At each tick of the Timer, the next square is filled with red, moving in a clockwise direction around the clock face. The instance variable, currentindex, stores which element of the POSITIONS array is the top left position of the square which is filled with red. Note: the position of the red square always cycles round and round the clockface in a clockwise direction. The user controls the JPanel using the arrow keys in the following way: The UP arrow key Whenever the user presses the UP arrow key, the top square is displayed in red, i.e., the square with the top left position given by the Point, POSITIONS[0]. Note that pressing the UP arrow key does not affect the Timer in any way. The DOWN arrow key Whenever the user presses the DOWN arrow key, the Timer stops/starts. If the Timer is currently running, pressing the DOWN arrow key causes the Timer to stop. If the Timer is currently stopped, pressing the DOWN arrow key causes the Timer to start. Below are some screenshots of the JPanel in action. The first four screenshots show the JPanel initially and during the first three ticks of the Timer. The last three screenshots show the JPanel as it completes one cycle of the clockface and begins the next cycle.......... Note: you MUST use the variables and constants given in the code.
Question/Answer Sheet - 21 - CompSci 101 with answers import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AJPanel extends JPanel //The top left positions of the squares in the clockface public static final Point[] POSITIONS = { new Point(70, 10), new Point(90, 30), new Point(110, 50), new Point(130, 70), new Point(110, 90), new Point(90, 110), new Point(70, 130), new Point(50, 110), new Point(30, 90), new Point(10, 70), new Point(30, 50), new Point(50, 30) ; public static final int SIZE = 10; private int currentindex; private Timer t; implements KeyListener, ActionListener { public AJPanel() { currentindex = 0; addkeylistener(this); t = new Timer(300, this); t.start(); public void actionperformed(actionevent e) { if (currentindex == POSITIONS.length - 1) { currentindex = 0; else { currentindex++; repaint(); public void paintcomponent(graphics g) { super.paintcomponent(g); g.setcolor(color.red); Point p = POSITIONS[currentIndex]; g.fillrect(p.x, p.y, SIZE, SIZE); g.setcolor(color.black); drawemptysquares(g);
Question/Answer Sheet - 22 - CompSci 101 with answers private void drawemptysquares(graphics g) { Point p; for( int i = 0; i < POSITIONS.length; i++) { p = POSITIONS[i]; g.drawrect(p.x, p.y, SIZE, SIZE); public void keypressed(keyevent e) { if (e.getkeycode() == KeyEvent.VK_UP ) { currentindex = 0; else if (e.getkeycode() == KeyEvent.VK_DOWN) { if (t.isrunning()) { t.stop(); else { t.start(); repaint(); public void keyreleased(keyevent e) { public void keytyped(keyevent e) { (10 marks)
Question/Answer Sheet - 23 - CompSci 101 with answers OVERFLOW PAGE (Please number the question(s) carefully and indicate clearly under the relevant question that you have overflowed to this page)
Question/Answer Sheet - 24 - CompSci 101 OVERFLOW PAGE (Please number the question(s) carefully and indicate clearly under the relevant question that you have overflowed to this page)