2002SCExamAnswers

2002SCExamAnswers - COMPSCI 101 THE UNIVERSITY OF AUCKLAND SECOND SEMESTER 2002 Campus City and Tamaki COMPUTER SCIENCE Principles of

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, 2002 Campus: City and Tamaki 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 There is also a page at the back for rough working. This page will not be marked. No Calculators are permitted Surname Forenames Student ID Login name Question Marks Out of Question 1 (Short answer) 10 Question 2 (Writing methods) 10 Question 3 (Desk-checking methods) 10 Question 4 (Classes) 15 Question 5 (ActionListener, MouseListener) 15 Question 6 (Bresenham's line algorithm) 20 Question 7 (Ethics) 20 Total 100 CONTINUED Candidate's Name:___________________ 1. 2 COMPSCI 101 What is the output shown by each of the following code fragments? (a) System.out.println(2+3+"^2+3^"+2+3); 5^2+3^23 (1 mark) (b) System.out.println(2/4*4.0+"^"+2.0/4*4); 0.0^2.0 (1 mark) (c) int a = 7; int b = 3; if( a % 3 == b % 2 ) System.out.println("Equal"); if( !(a != 3) || !(b == 3) ) System.out.println("Not"); Equal (2 marks) (d) int a = 7; int b = 3; if( a==7 && ( a!=4 && b+4==a) ) System.out.println("And"); if( a==3 || (a==7 && b==4) || (b!=7 || b==7) ) System.out.println("Or"); And Or (2 marks) (e) System.out.println("Before"); for(int i=0; i<0; i++) System.out.println("Test" + i); System.out.println("After"); Before After (1 mark) CONTINUED Candidate's Name:___________________ (f) 3 COMPSCI 101 int a = 4; int b = 5; int c = 6; int d = 7; if( a > b && b > c ) System.out.println("a>c"); else if( (a+d) == (b+c) ){ if( a-b < d-c) if( a == d ) System.out.println("b > c"); else if( a > d ) System.out.println("c > b"); else System.out.println("unknown"); } else System.out.println("Confused yet?"); System.out.println("I am"); unknown I am (2 marks) (g) int k=0; int i=0; for(i=0; i<3; i++); { System.out.println("Test" + i); if(k == 0) k = 2; else k = 0; System.out.println(k); } Test3 2 (1 mark) CONTINUED Candidate's Name:___________________ 4 COMPSCI 101 2. Write a method called scramble() which is used to rearrange the letters in a given String. The letters should be rearranged into random order, based on a "key" value which is used as the "seed" for the pseudo-random number generator used by Java. Your method should accept a S tring and an i nt as parameters, and should return a String which contains the same letters, but rearranged into random order. If the scramble() method is called on two separate occasions with the same parameters, then the characters will be arranged in the same order on both occasions. All of the letters in the original String should be used (including all spaces and punctuation). Example: Executing the statements: System.out.println( System.out.println( System.out.println( System.out.println( scramble( scramble( scramble( scramble( "Hello", 100 "Hello", 200 "Have a nice "Hello", 100 ) ); ) ); day", 1234 ) ); ) ); would produce the output: Hlloe olelH ie Hd ncyvaeaa Hlloe You should use the Random class in order to select the letters in the same order given the same key value. The following extract from the Java API might prove useful here (note that you do not have to use all the methods listed below): java.util.Random Constructor Summary Random() Creates a new random number generator. Random(long seed) Creates a new random number generator using a single long seed: Method Summary int nextInt() Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. void setSeed(long seed) Sets the seed of this random number generator using a single long seed. CONTINUED Candidate's Name:___________________ 5 COMPSCI 101 Complete the application written here: //import any required packages here import java.util.*; public class TestScramble{ //Write your method here private static String scramble( String s, int key ){ Random r = new Random(key); String result = ""; while(s.length() > 0){ int i = r.nextInt(s.length()); result += s.charAt(i); s = s.substring(0,i) + s.substring(i+1); } return result; } //Given here is some code which might be used to test your //method //Your method *must* produce the correct answer when different //test cases are used public static void main(String args){ System.out.println( scramble( "Hello", 100 ) ); System.out.println( scramble( "Hello", 200 ) ); System.out.println( scramble( "Have a nice day", 1234 ) ); System.out.println( scramble( "Hello", 100 ) ); } } (10 marks) CONTINUED Candidate's Name:___________________ 6 COMPSCI 101 3. Desk-check the following code using the technique of diagrams shown in lectures. Show both the diagram used to desk-check the code (on facing page) and the output produced (below). public class Test{ private static int method01(){ System.out.println("Method 01"); return 6; } private static int method02(int i){ System.out.println("Method 02"); int a = 5; if( i % 2 == 0 ) a = method01(); return a; } private static int method03(int i){ System.out.println("Method 03"); int a = method02( i + 1 ); return i*a; } private static int method04(int a, int b){ System.out.println("Method 04"); int i = method03(a); b = method02( method01() ); return i+b; } public static void main(String args){ System.out.println( method04(2,3) ); } } Show your output here: Method Method Method Method Method Method 16 04 03 02 01 02 01 (4 marks) CONTINUED Candidate's Name:___________________ 7 COMPSCI 101 Show the diagram here: main 16 method04( 2, 3 ) int a = 2 int b = 3 int i = 10 10 method03( 2 ) 6 6 method01( ) int i = 2 int a = 5 5 method02( 3 ) 6 method02( 6 ) int i = 6 int a = 5 int i = 3 int a = 5 6 6 method01( ) (6 marks) Notes: Although a systematic method of desk-checking using diagrams was shown in lectures, students were not required to follow the system exactly, but were encouraged to use a consistent approach to diagrams. • Each method should be clearly shown. • Values stored in variables, and changes to those variables should be shown • Any parameters should be treated as local variables and shown Arrows should link methods which call other methods. CONTINUED Candidate's Name:___________________ 8 COMPSCI 101 4. Below is the TestQ class definition which you need to complete. An application which uses the TestQ class is shown on the next page. This TestQ class represents test questions. Each new TestQ instance has a unique questionID number set from the static variable nextID. public class TestQ { //static variable used to assign an id to each new Question private static int nextID = 1; private int questionID; //id of question private int marksOutOf; //number of marks question is out of private double averageMk; //average mark for question private int level; //level of difficulty of question private String description; //description of question public TestQ(int marksOutOf, double ave, String desc, int lev){ questionID = nextID; nextID++; this.marksOutOf = marksOutOf; averageMk = ave; description = desc; level = lev; } public .int getMarksOutOf(){ return marksOutOf; } public .double getAverageMk(){ return averageMk; } public . String toString(){ return questionID+": Level "+level+" Question: "+" "+ description+", average: "+averageMk+"/"+marksOutOf; } CONTINUED Candidate's Name:___________________ 9 COMPSCI 101 public . boolean hasSameLevel( .TestQ otherQ ){ return level==otherQ.level; } public boolean descriptionContainsWd( .String wd ){ return description.indexOf(wd)>-1; } } The Q4 application shown below uses the TestQ class. Complete the TestQ class definition above so that the Q4 application compiles and gives the output shown on the next page. public class Q4{ public static void main(String args){ TestQ q1, q2, q3; q1 = new TestQ(10,8.5,"declaring variables",1); q2 = new TestQ(20,14.6,"method parameter passing",3); q3 = new TestQ(10, 6.5, "method return types",3); System.out.println(q1.toString()); System.out.println(q2.toString()); System.out.println(q3.toString()); System.out.println(); System.out.println("Questions with better average than 70%:"); if (q1.getAverageMk()/q1.getMarksOutOf()>0.7) System.out.println(q1.toString()); if (q2.getAverageMk()/q2.getMarksOutOf()>0.7) System.out.println(q2.toString()); if (q3.getAverageMk()/q3.getMarksOutOf()>0.7) System.out.println(q3.toString()); System.out.println(); System.out.println("Questions on methods"); if (q1.descriptionContainsWd("method")) System.out.println(q1.toString()); if (q2.descriptionContainsWd("method")) System.out.println(q2.toString()); if (q3.descriptionContainsWd("method")) CONTINUED Candidate's Name:___________________ 10 System.out.println(q3.toString()); COMPSCI 101 System.out.println(); if (q1.hasSameLevel(q2) && q1.hasSameLevel(q3)) System.out.println("q1, q2, q3 have the same level of difficulty"); else { if (q1.hasSameLevel(q2)) System.out.println("q1, q2 have the same level of difficulty"); if (q1.hasSameLevel(q3)) System.out.println("q1, q3 have the same level of difficulty"); if (q2.hasSameLevel(q3)) System.out.println("q2, q3 have the same level of difficulty"); } } } The output obtained when the Q4 application is executed with the completed TestQ class is shown below. >java Q4 1: Level 1 Question: 2: Level 3 Question: 3: Level 3 Question: declaring variables, average: 8.5/10 method parameter passing, average: 14.6/20 method return types, average: 6.5/10 Questions with better average than 70%: 1: Level 1 Question: declaring variables, average: 8.5/10 2: Level 3 Question: method parameter passing, average: 14.6/20 Questions on methods 2: Level 3 Question: 3: Level 3 Question: method parameter passing, average: 14.6/20 method return types, average: 6.5/10 q2, q3 have the same level of difficulty (15 marks) CONTINUED Candidate's Name:___________________ 11 COMPSCI 101 5. The following application creates an instance of a class called Q5Frame: public class Q5{ public static void main(String args){ Q5Frame theFrame = new Q5Frame("Question 5",10, 20, 250,150); } } Below is the definition of the Q5Frame class which you need to complete. The behaviour of the Q5Frame is discussed on the pages following the Q5Frame class definition shown below. import java.awt.*; import java.awt.event.*; public class Q5Frame extends Frame implements ActionListener, MouseListener{ private final int SIZE = 20; //size of circle and square at //each end of the line private int x1,y1; //x,y position of the start point of the line private int x2,y2; //x,y position of the end point of the line private TextField x1T, y1T; //TextFields which store the x,y //values of the start point of the line private boolean isSelected; //-------------------------------------------------------------//-------------- Constructor for the Frame --------------------//-------------------------------------------------------------- public Q5Frame(String title, int top, int left, int width, int height){ setTitle(title); setBounds(top,left, width, height); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ dispose(); System.exit(0); }}); setLayout(new FlowLayout()); x1T = new TextField(6); //create the 2 TextFields y1T = new TextField(6); x1T.addActionListener(this); y1T.addActionListener(this); addMouseListener(this); add(x1T); add(y1T); isSelected = false; CONTINUED Candidate's Name:___________________ reset(); show(); } 12 COMPSCI 101 //-------------------------------------------------------------//------------------------- Set the initial state -------------//-------------------------------------------------------------- public void reset(){ x1 = 150; //set initial value for x1, y1 y1 = 100; x2 = 200; //set initial value for x2, y2 y2 = 60; x1T.setText("150");//set initial values for the 2 TextFields y1T.setText("100"); isSelected = false; } //-------------------------------------------------------------//------------------------- Handle ActionEvents ---------------//-------------------------------------------------------------- public void actionPerformed(ActionEvent e){ x1 = Integer.parseInt(x1T.getText()); y1 = Integer.parseInt(y1T.getText()); repaint(); } //-------------------------------------------------------------//------------------------- Handle MouseEvents ----------------//-------------------------------------------------------------- public void mousePressed(MouseEvent e){ int pressX = e.getX(); int pressY = e.getY(); if(pressX>x2-SIZE/2 && pressX<x2+SIZE/2 && pressY>y2-SIZE/2 && pressY<y2+SIZE/2) isSelected = true; repaint(); } public void mouseReleased(MouseEvent e){ if (isSelected){ x2 = e.getX(); y2 = e.getY(); isSelected = false; repaint(); } } CONTINUED Candidate's Name:___________________ 13 public void mouseEntered(MouseEvent e){ } public void mouseExited(MouseEvent e){ } public void mouseClicked(MouseEvent e){ } COMPSCI 101 //-------------------------------------------------------------//----------- Display the line in the Frame -------------------//-------------------------------------------------------------- public void paint(Graphics g){ g.setColor(Color.blue); g.fillOval(x1-SIZE/2,y1-SIZE/2, SIZE, SIZE); g.drawLine(x1,y1,x2,y2); if (isSelected) g.setColor(Color.red); else g.setColor(Color.blue); g.fillRect(x2-SIZE/2,y2-SIZE/2, SIZE, SIZE); } } Complete the Q5Frame class definition above so that the Q5Frame behaves as follows: The Q5Frame first appears displaying a line from the point (x1, y1) [the start point of the line which is surrounded by a filled circle of size 20] to the point (x2, y2) [the end point of the line which is surrounded by a filled square of size 20]. Initially (x1, y1) which is the start point for the line has values (150, 100) and (x2, y2) which is the end point for the line has values (200, 60). Initially the line, the circle and the square are all displayed in the colour blue. The Q5Frame contains two TextFields [called x1T, y1T in the Q5Frame class definition]; these two TextFields always contain the values of the start point for the line [initially these values are 150 for x1 and 100 for y1]. When the user enters new values for the start point of the line in the two TextFields and presses ENTER in either TextField the start position of the line is set to the new values entered by the user in the two TextFields. The left hand TextField, x1T, contains the x value for the start point of the line.and the right hand TextField , y1T, contains the y value for the start point of the line. Note: the end point of the line does not change when the user changes the values for the start point of the line. The two screenshots below show the Q5Frame when CONTINUED Candidate's Name:___________________ 14 the user enters new values for the start point of the line. COMPSCI 101 Here the user has entered 50, 130 in the two TextFields and has pressed ENTER in one of the TextFields. The line displayed now begins at position (50,130). Note: the end of the line has not changed. Here the user has entered 220, 120 in the two TextFields and has pressed ENTER in one of the TextFields. The line displayed now begins at position (220,120). Note: the end of the line has not changed. In the Q5Frame the end point for the line is enclosed in a filled square of size 20; whenever the user presses the mouse inside this square area the square area should be displayed in red showing that the end point is selected. If the user has selected the end point of the line b y pressing the mouse inside the square and then releases the mouse in a new position inside the Q5Frame then this release point of the mouse becomes the new end point for the line; the square area surrounding the end point is now filled with blue showing that the end point is no longer selected. Note: the start point of the line does not change when the user changes the position of the end point for the line. The four screenshots below show Q5Frame when the user presses and releases the mouse to change the position of the end point of the line. CONTINUED Candidate's Name:___________________ 15 COMPSCI 101 Here t he u ser h as p ressed the mouse i nside t he s quare area surrounding the end point of the line. T he s quare area i s now displayed in red showing that the end point is selected. The user has now released the mouse in a new position inside the Q5Frame. The end point for the line has changed t o the position where the user released the mouse. The square area is now displayed in blue showing that the end point is no longer selected. Note: the start point for the line has not changed. Here the user has pressed the mouse i nside t he s quare area surrounding the end point for the line. The square area is now displayed in red showing that the end point is selected. The user has now released the mouse in a new position inside the Q5Frame. The end point for the line has changed to t he p osition w here t he u ser released the mouse. The square area is now displayed in blue showing that the end point is no longer selected. Note: the start point of the line has not changed. (15 marks) CONTINUED Candidate's Name:___________________ 16 COMPSCI 101 6. Consider a line that is to be drawn between the points (0,0) and (10,3). a) Using any method you choose, identify the eleven grid points that lie closest to this line. (6 marks) b) Recall Bresenham's line algorithm discussed in lectures and studied in lab 9. Java code for this algorithm is given below. Warning: the code actually contains a subtle error, and so the program will NOT give the "correct" output. You must show the values this program will produce. void line( int x1, int y1, int x2, int y2 ) { int dx = x2 - x1; int dy = y2 - y1; int e = 0; int y = y1; for( int x = x1; x <= x2; x++ ) { plot( x, y ); if( 2*(e + dy) > dx ) e = e + dy; else { y = y + 1; e = e + dy - dx; } } } CONTINUED Candidate's Name:___________________ 17 COMPSCI 101 Perform a "desk check" using the Bresenham code above, using the same input as in part a); i.e., the call will be to line(0,0,10,3). Show the values of the variables x, e and y at each iteration of the loop. (10 marks) c) Identify and correct the error in the algorithm. (4 marks) CONTINUED Candidate's Name:___________________ 18 COMPSCI 101 7. Ethics a) Name a "prima facie" principle. (1 mark) b) One of the reasons computers raise new and serious problems for society is the quantity and speed by which information can be stored, retrieved and transmitted. Give TWO additional reasons for the problems computers raise. (4 marks) c) Newspaper headlines reported the Therac-25 incidents as being caused by a "software bug". Identify THREE other causal factors identified by Leveson and Turner. CONTINUED Candidate's Name:___________________ 19 COMPSCI 101 (3 marks) d) Recall the ethical case you were assigned in assignment five. i) Give a concise summary of the case (4 marks) ii) Briefly describe the ethical principles at stake CONTINUED Candidate's Name:___________________ 20 COMPSCI 101 (4 marks) iii) What decision did you come to, and what justification did you use? (4 marks) CONTINUED Candidate's Name:___________________ 21 COMPSCI 101 Overflow Sheet Write the question number next to your answer. You must ALSO indicate in the allotted space that you have used the overflow sheet. CONTINUED Candidate's Name:___________________ 22 COMPSCI 101 Overflow Sheet Write the question number next to your answer. You must ALSO indicate in the allotted space that you have used the overflow sheet. CONTINUED 23 Rough Working COMPSCI 101 You may remove this page from the exam script if you wish. This page will not be marked. CONTINUED 24 Rough Working COMPSCI 101 You may remove this page from the exam script if you wish. This page will not be marked. _______________________ CONTINUED ...
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