Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Similar documents
Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Page 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Page 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Fall 2017 CISC124 10/1/2017

Page 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Fundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Contents Chapter 1 Introduction to Programming and the Java Language

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

Fall 2017 CISC124 9/27/2017

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Week 6: Review. Java is Case Sensitive

Introduction to Programming Using Java (98-388)

Language Features. 1. The primitive types int, double, and boolean are part of the AP

CS 180 Final Exam Review 12/(11, 12)/08

package As7BattleShip;

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Final Exam CS 251, Intermediate Programming December 13, 2017

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Midterm assessment - MAKEUP Fall 2010

Chapter 6 Introduction to Defining Classes

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

COURSE DESCRIPTION. John Lewis and William Loftus; Java: Software Solutions; Addison Wesley

Window Interfaces Using Swing. Chapter 12

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

15CS45 : OBJECT ORIENTED CONCEPTS

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

Starting Out with Java: From Control Structures Through Objects Sixth Edition

COP 3330 Final Exam Review

CSE 142 Su01 Final Exam Sample Solution page 1 of 7

Index COPYRIGHTED MATERIAL

This page intentionally left blank

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

(2½ hours) Total Marks: 75

Java Just in Time: Collected concepts after chapter 22

Example: Building a Java GUI

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Example: Building a Java GUI

This exam is closed textbook(s) and closed notes. Use of any electronic device (e.g., for computing and/or communicating) is NOT permitted.

CS 349 Midterm Exam Spring 2014

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Come & Join Us at VUSTUDENTS.net

Chapter 5: Enhancing Classes

Java Programming Lecture 6

CO Java SE 8: Fundamentals

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

VALLIAMMAI ENGINEERING COLLEGE

Objects and Iterators

Arrays and ArrayLists. David Greenstein Monta Vista High School

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

This page intentionally left blank

Mobile MOUSe JAVA2 FOR PROGRAMMERS ONLINE COURSE OUTLINE

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Just in Time: Collected concepts after chapter 18

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Agenda. Container and Component

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Programming Exercise. Scribbler

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

About this exam review

TeenCoder : Java Programming (ISBN )

COMP16121 Sample Code Lecture 1

PIC 20A GUI with swing

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CS 134 Programming Exercise 7:

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Super-Classes and sub-classes

DCS235 Software Engineering Exercise Sheet 2: Introducing GUI Programming

Transcription:

QUEEN'S UNIVERSIY SCHOOL O COMPUING CMPE212, ALL ERM, 2011 INAL EXAMINAION 15 December 2011, 2pm, Grant Hall Instructor: Alan McLeod HAND IN Answers Are Recorded on Question Paper SOLUION If the instructor is unavailable in the examination room and if doubt exists as to the interpretation of any problem, the candidate is urged to submit with the answer paper a clear statement of any assumptions made. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. Please write your answers in the boxes provided and write your student number on each page. Extra space is available on the last page of the exam. he back of any page can be used for rough work. his exam is three hours long and refers exclusively to the use of the Java language. Comments are not required in the code you write. or full marks, code must be efficient as well as correct. his is a closed book exam. No computers or calculators are allowed. Student Number: Problem 1: / 20 Problem 4: / 25 Problem 2: / 20 Problem 5: / 20 Problem 3: / 15 OAL: / 100

Student Number: Page 2 of 16 Problem 1) [20 marks]: Methods, loops, arrays and passing by reference. a) Write a method that accepts a two-dimensional array of int values of any size and returns the average of all the values in the array as a double. You must use for/each loops, and may assume that the supplied array is not null and is rectangular (ie. each row has the same number of values). or example, if the method is supplied with the 2D array: 1, 2, 2, 2, 3 1, 1, 2, 1, 1 2, 3, 1, 2, 3 it would return the value 1.8 which is the sum of all values (27) divided by the number of values (15). If you cannot remember how to use for/each loops you can use normal for loops to obtain part marks. public static double avgval(int[][] nums) { double sum = 0; for (int[] row : nums) for (int num : row) sum += num; int numnums = nums.length * nums[0].length; return sum / numnums;

Student Number: Page 3 of 16 Problem 1, Cont.) b) Write another method that cannot use the method you wrote for part a), that accepts a twodimensional array of int of any size, returns the sum of all values in this array as an int, and supplies the sums of each row and of each column in two separate arrays of int. As for part a), you may assume that the supplied 2D array is not null and is rectangular. You may assume that the supplied 1D arrays contain only zeros, but must check to make sure that array sizes match the size of the 2D array. If you find an error, print out an appropriate message and return zero. or full marks you can only use one set of nested loops for this method, but may use normal for loops. or example, if this method is supplied with the 2D array from part a) it would return the sum 27 and supply the row sum array 10, 6, 11 and the column sum array 4, 6, 5, 5, 7. public static int allsums(int[][] nums, int[] rowsums, int[] colsums) { int numrows = nums.length; int numcols = nums[0].length; int sum = 0; int anum; if (rowsums.length!= numrows colsums.length!= numcols) { System.out.println("Array sizes do not match!"); return 0; int row, col; for(row = 0; row < numrows; row++) for(col = 0; col < numcols; col++) { anum = nums[row][col]; sum += anum; rowsums[row] += anum; colsums[col] += anum; return sum;

Student Number: Page 4 of 16 Problem 2) [20 marks]: Methods, text file output, string methods and try-with-resources block. a) In the box below, write a method called process() that cleans up a String so that it can be written to a file (in part b)). Cleaning up will require that all leading and trailing whitespace is removed and any trailing commas (commas at the end of the string) are removed. If the method process() is invoked with a null or empty string it can just return that string. Here are a few String class methods, some of which might be useful: length() equals(otherstring) trim() charat(position) substring(start) substring(start, endplusone) indexof(searchstring) indexof(searchstring, start) replace(oldchar, newchar) // returns the length of the string as an int // returns true if otherstring matches the String // returns the String without leading and/or trailing // whitespace // returns the char at the specified position // returns the right part of the String, starting from // position start // returns the String starting from position start and // ending at position endplusone 1 // returns the position of the first occurrence of // searchstring in the String // returns the position of the first occurrence of // searchstring in the String searching from position start // returns a String that has all occurrences of // oldchar replaced with newchar public static String process(string dirty) { if (dirty == null dirty.length() == 0) return dirty; String clean = dirty.trim(); int len = clean.length(); while (len > 1 && clean.charat(len 1) == ',') { clean = clean.substring(0, len 1).trim(); len = clean.length(); return clean;

Student Number: Page 5 of 16 Problem 2, Cont.) b) In the box below write a method called writeext() that accepts a filename as a String and an ArrayList<String> object that contains all the strings that need to be saved to the file. You do not need to do any error checking on either parameter and you can assume that the ArrayList is neither empty nor null. he method should return the number of lines written if the text is saved without error, a zero otherwise. A BufferedWriter resource object is returned by the static method.newbufferedwriter() owned by the iles class. his method accepts a Path object and a Charset object. he Path object is created by supplying the filename string to the static.get() method invoked from the Paths class. he Charset object can be created by the code: Charset charset = Charset.forName("US ASCII"); he non-static.write() method of the BufferedWriter resource object, instantiated as described above, can be invoked with a String argument and will write that string to the file. he file should contain one string from the ArrayList per line. You must invoke your process() method from part a) (assume it is in the same class as writeext()) on each string before writing it to the file. he resource creation process and the writing process could throw an IOException object which must be caught. An ArrayList object owns the methods.size() and.get(), where.get() accepts an int value and returns the object at the given position in the data structure. You may assume that all required classes have been imported from the Java API. public static int writeext(arraylist<string> text, String filename) { int numlines = 0; Charset charset = Charset.forName("US ASCII"); Path file = Paths.get(filename); try (BufferedWriter writer = iles.newbufferedwriter(file, charset)) { for (String line : text) { writer.write(process(line) + "\r\n"); numlines++; catch (IOException err) { return 0; return numlines;

Student Number: Page 6 of 16 Problem 3) [15 marks]: Qualitative Java. Write a or on the line before each of the following statements to indicate if it is rue or alse: 1. All Boolean comparisons must be carried out before arithmetic operations are evaluated in a Java expression. 2. he && operator always evaluates the expressions on both sides of the operator. 3. Casting operations have a higher precedence than arithmetic operations in any expression. 4. he ++ post increment operator carries out the increment after the variable is used in an expression. 5. If an expression contains a non-void method call that results in an exception being thrown by the method, the returned value from the method call can still be used in the rest of the expression. 6. Switch statements can be used with floating point values to see if they lie in certain, predefined value ranges. 7. Any switch statement construct can be built using a chained if construct. 8. A for each loop must be coded to use the index value to obtain collection elements. 9. hrown exceptions will be propagated to the main method if they are not caught in a try/catch block. 10. Passing an array into a method involves the creation of a new copy of that array in the method. 11. Automatic un-boxing can simplify the use of Wrapper classes with Generic classes. 12. he Math class contains only static methods and attributes. 13. Strings are mutable objects. 14. Arrays are mutable objects. 15. A object that extends Jrame inherits a frame with a title bar and the normal window title bar controls.

Student Number: Page 7 of 16 Problem 3, Cont.) 16. Components laid down in a JPanel using lowlayout will always be touching each other when displayed. 17. A component placed in the Center position of a BorderLayout will swell to touch the edges of that position. 18. A GridLayout type object can be instantiated using a constructor that accepts the number of rows and columns to be used in the grid. 19. he text attribute of a JLabel in a running GUI program can only be changed in code through a mutator. 20. A Jextield component can display multiple lines of text. 21. here is more than one listener class that can respond to mouse initiated events. 22. System-generated component re-draws invoke the paint(graphics g) method for that component. 23. Code-generated component re-draws can also be carried out by invoking the paint(graphics g) method directly. 24. o invoke a component s repaint() method you must supply the Graphics object associated with that component to the repaint() method. 25. Windows created in Java 7 do not have to be rectangular in shape. 26. Many listener objects can be attached to a imer thread. 27. Once an instance of a hread object is started, it cannot be stopped until the application owning the thread is finished. 28. An exception is used to stop a hread object. 29. An exception is used to stop a imer object. 30. It is possible to speed up a Quicksort method by using the ork/join framework to spread the task over multiple processor cores.

Student Number: Page 8 of 16 Problem 4) [25 marks]: Encapsulation. Your hardware store manager has asked you to create a database to store information on toilets. o do this, you need to create a fully encapsulated class that will make the operation of the database easy and safe to program. he information you need to use to describe a toilet is: Colour: white, pink or beige. lush volume in litres: between 4.8 and 15 Seat size: normal or elongated A legal toilet must meet the criteria provided above for each attribute. If the seat size for a toilet is not specified when the class is instantiated, assume that it is of normal size. he flush volume, in litres, must be a floating point number and lie between 4.8 and 15 litres inclusive. A colour string can be provided in any letter case, but must match one of the three colours provided above. If a colour is not provided, then assume it is white. Compare strings using the.equalsignorecase(otherstring) String class method. Note that this means you will need four constructors. Supply mutators and accessors for all three attributes. oilet equality is defined as the colour and seat size being exactly equal (ignoring case) and the flush volume agreeing to within a tenth of a litre. Your equals() method must override the equals() method of the Object class. oilets will be sorted based only on their flush volume, which forms the basis for your compareo() method. You must also supply a clone() method and a tostring() method. A string representation would look like: A white toilet with a standard seat and a flush volume of 5.0 litres. hrow an Illegaloilet exception object if an attempt is made to set or alter any of the attributes to illegal values. Write the Illegaloilet exception class below and the oilet class on the following three pages. public class Illegaloilet extends Exception { public Illegaloilet(String s) { super(s); public Illegaloilet() { super("attempt to create an illegal toilet!");

Student Number: Page 9 of 16 Problem 4, Cont.) public class oilet { private String colour; private double flush; private String seat; // Constructors public oilet(string col, double flu, String sit) throws Illegaloilet { setcolour(col); setlush(flu); setseat(sit); public oilet(string col, double flu) throws Illegaloilet { this(col, flu, "normal"); public oilet(double flu, String sit) throws Illegaloilet { this("white", flu, sit); public oilet(double flu) throws Illegaloilet { this("white", flu, "normal"); // Mutators public void setcolour(string col) throws Illegaloilet { if (col.equalsignorecase("white") col.equalsignorecase("beige") col.equalsignorecase("pink")) colour = col; else throw new Illegaloilet("Illegal colour: " + col); public void setlush(double flu) throws Illegaloilet { if (flu >= 4.8 && flu <= 15) flush = flu; else throw new Illegaloilet("Illegal flush size: " + flu); public void setseat(string sit) throws Illegaloilet { if (sit.equalsignorecase("normal") sit.equalsignorecase("elongated")) seat = sit; else throw new Illegaloilet("Illegal seat: " + sit);

Student Number: Page 10 of 16 Problem 4, Cont.) // Accessors public String getcolour() { return colour; public double getlush() { return flush; public String getseat() { return seat; public String tostring() { String s = "A " + colour + " toilet with a "; s += seat + " and a flush volume of " + flush + " litres."; return s; public boolean equals(object obj) { if (obj instanceof oilet) { oilet other = (oilet)obj; if (other.colour.equals(colour) && other.seat.equals(seat)) if (Math.abs(other.flush flush) <= 0.1) return true; return false; public int compareo(oilet other) { return (int)(10 * (other.flush flush)); public oilet clone() { oilet other = null; try { other = new oilet(colour, flush, seat); catch (Illegaloilet it) { return other; // end oilet

Student Number: Page 11 of 16 Problem 4, Cont.)

Student Number: Page 12 of 16 Problem 5) [20 marks]: GUI coding. Here is the window that was generated by the code given to you in problem 3 of Quiz 4: his time you must work backwards and write the code that generates this layout. Part of the program is given for you on the next page you need to finish it. inish the layout code and the code that adds the functionality to the Switch button. You will remember that the button switches the two labels. When clicked once, the Switch button changes the left label to read Goodbye! and the right label to read Hello!. Clicking on the button again sets the labels back to how they appear above. Continued button clicking just keeps switching labels. You cannot and do not need to import any other classes. You can use only GridLayout, BorderLayout and lowlayout layout managers. Remember that the layout manager used by a component like a JPanel can be set using the.setlayout() mutator or an instantiated layout manager object can be supplied to the constructor of the JPanel. he.add() method can be used to add components to an instantiated JPanel container. Remember that the ActionListener interface will force you to implement the method: public void actionperformed(actionevent e) he.setext() mutator allows you to change the text of a JLabel object. You can get the current text of a label using the accessor method.getext(), which returns a String object. You may assume that there is some other class with a main method that displays this window, and you do not have to write this other class, nor include a main method in your Jrame class.

Student Number: Page 13 of 16 Problem 5, Cont.) import javax.swing.jrame; import javax.swing.jbutton; import javax.swing.jpanel; import javax.swing.jlabel; import javax.swing.jextield; import java.awt.lowlayout; import java.awt.ont; import java.awt.borderlayout; import java.awt.gridlayout; import java.awt.event.actionevent; import java.awt.event.actionlistener; public class GUIExamProblem extends Jrame { private final int WIDH = 800; private final int HEIGH = 160; private String message1 = "Hello!"; private String message2 = "Goodbye!"; private JLabel messagelabel1 = new JLabel(message1); private JLabel messagelabel2 = new JLabel(message2); public GUIExamProblem () { super(); setdefaultcloseoperation(jrame.exi_on_close); setitle("gui Exam Problem"); setsize(widh, HEIGH); setlayout(new BorderLayout()); ont myont = new ont("arial", ont.plain, 26); messagelabel1.setont(myont); messagelabel1.sethorizontalalignment(jlabel.righ); messagelabel2.setont(myont); messagelabel2.sethorizontalalignment(jlabel.le); JButton switchmessagebutton = new JButton("Switch"); switchmessagebutton.setont(myont); Jextield textbox = new Jextield(8); textbox.setont(myont); // inish the rest of this class starting on the next page:

Student Number: Page 14 of 16 Problem 5, Cont.) switchmessagebutton.addactionlistener(new MessageButtonListener()); JPanel toppanel = new JPanel(new GridLayout(1, 3)); JPanel bottompanel = new JPanel(new lowlayout()); toppanel.add(messagelabel1); toppanel.add(textbox); toppanel.add(messagelabel2); bottompanel.add(switchmessagebutton); add(toppanel, BorderLayout.NORH); add(bottompanel, BorderLayout.SOUH); // end constructor private class MessageButtonListener implements ActionListener { public void actionperformed (ActionEvent e) { if (messagelabel1.getext().equals(message1)) { messagelabel1.setext(message2); messagelabel2.setext(message1); else { messagelabel1.setext(message1); messagelabel2.setext(message2); // end actionperfomed // end MessageButtonListener // end GUIExamProblem class

Student Number: Page 15 of 16 Problem 5, Cont.)

Student Number: Page 16 of 16 (extra space)