[go: up one dir, main page]

0% found this document useful (0 votes)
55 views10 pages

Dublin City University: Semester Two Examinations 2009

This document provides instructions and questions for an exam on computer programming. It includes 3 questions, with question 1 having 8 parts asking about method return types, string operations, and array processing. Question 2 asks the student to write a program to analyze word frequencies in a text. Question 3 provides a Date class and asks the student to write an Employee class, Staff class, and a program to test them by creating an employee file and displaying senior employees.

Uploaded by

David Mc Hugh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views10 pages

Dublin City University: Semester Two Examinations 2009

This document provides instructions and questions for an exam on computer programming. It includes 3 questions, with question 1 having 8 parts asking about method return types, string operations, and array processing. Question 2 asks the student to write a program to analyze word frequencies in a text. Question 3 provides a Date class and asks the student to write an Employee class, Staff class, and a program to test them by creating an employee file and displaying senior employees.

Uploaded by

David Mc Hugh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

DUBLIN CITY UNIVERSITY

SEMESTER TWO EXAMINATIONS 2009


MODULE:
(Title and Code)

Computer Programming II CAI 66

COURSE:

B.Sc. in Computer Applications International Foundation Certificate 1 Dr Paul Gibson Dr Frank Bannister Prof. J. M. Morris (Ext. 8419)

YEAR: E M MINERS:

TIME ALLOWED: INSTRUCTIONS:

3 Hours
Answer all questions. There are three questions. Question 1 has eight parts. Answers may draw on classes, methods, etc. in the Java library that are listed in the reference provided at the end of the paper; the use of the Java library is limited to this.

Requirements for this paper Please tick (X) as appropriate

-'

Log Table Graph Paper Attached Answer Sheet Statistical Tables Floppy Disk ctuarial Tables

THE USE OF PROGRAMMABLE OR TEXT STORING CALCULATORS IS EXPRESSLY FORBIDDEN


Please note that where a candidate answers more than the required number of , questions, the examiner will mark all questions attempted and then select the highest scoring ones.

PLEASE DO NOT TURN OVER THIS PAGE UNTIL ASKED TO DO SO

Question 1

(a)

Supply the return type (or v o i d ) of the following methods, or indicate that none is possible. (i)
s t a t i c . . . f l ( i n t x, i n t y) r e t u r n ( x > y );
{

(ii)

s t a t i c . . . 20 { System. o u t . p r i n t ("true") ;

(iii)

s t a t i c . . . 3 ( ) { return "true";

(i~)

s t a t i c . . . f 4 ( i n t x, i n t y) { i f ( y !=O) r e t u r n x / y ; e l s e S y s t e m . o u t . p r i n t ( " e r r o r " ) ;

(v)

s t a t i c . .. f5 { i f (y!=O) r e t u r n x/y;

(~i)

s t a t i c . . . f 6 ( d o u b l e x) { r e t u r n Math.round(x);
1

[6 marks] (b) Let s be a given variable of type S t r i n g . Supply the missing expressions in the following Java assignment statements, noting the type of the variable being assigned to in each case.
boolean b = . . . s begins with t h e t h r e e l e t t e r s "cat" . . . ; i n t j = . . . t h e index of t h e f i r s t occurrence of " c a t " i n s , o r -1 i f " c a t " d o e s n o t o c c u r i n s . . . ; int k = . t h e index of t h e f i r s t occurrence of " c a t " i n s , o r t h e l e n g t h o f s i f " c a t " d o e s n o t o c c u r i n s . . .; S t r i n g t = . . t h e f i r s t f i v e c h a r a c t e r s of s w i t h any lower c a s e l e t t e r s c o n v e r t e d t o u p p e r c a s e ( y o u may assume t h e l e n g t h of s i s a t l e a s t 5 ) . . . . ;

[6 marks] (c) Write a Java program which prints a string a multiple number of times, where the string and the multiple are supplied at the command line. For example, invoking j a v a dog 3 should result in dogdogdog being printed. [6 marks] Con~pletethe following method for computing the index of the first negative number in an integer array, or -1 if the array contains no negatives. For example, fi r s t N e g (b)should return 2 if b contains 9 8 - 6 5 - 3 2 and it should return -1 if it contains 9 6 8 3 .
page 2 of 10

(d)

CAI66

s t a t i c i n t firstNeg ( i n t [ ] b) {

[6 marks]
(e) Write a class P o i n t to represent 2-dimensional points (where the point coordinates are of type double). The class should contain the two standard constructors, i.e. one with no arguments, and one with an argument for each instance variable. It should also include instance methods g e t for reading the coordinates of a point from the keyboard, and t o s t r i n g for computing a string representation of the point in a form typified by (3.14,2.71). [6 marks] Add to class P o i n t of part (e) an instance method called m i d p o i n t which returns an object of type P o i n t representing the midpoint of two points, where one of the points is supplied as a parameter and the other is ,the current point (i.e. the point provided by the local instance variables). Note that m i d p o i n t returns a new P o i n t object. [6 marks] Making good use of class P o i n t from parts (e) and (f) above, write a program which reads two points and prints their midpoint. The input consists of two lines where each line contains the x- and y-coordinates of a point. An example of inputloutput follows, with input indicated by bolding:
E n t e r two p o i n t s 2.1 3.2 3.0 2.8 The m i d p o i n t i s (2.55,3.0)

(f)

(g)

[6 marks]
(h) The following four algorithms are each executed on an array b of 1 million integers. Write them down in the order of what you believe would be the likely execution times, from slowest to fastest. (i) (ii) (iii) (iv) Reverse b (i.e. swap 1st & last elements, 2nd & 2nd last elements, etc.) Sort b using selection sort. Sort b using quicksort. Find the first negative in b.

If selection sort takes 100 seconds to sort b, about how long w o ~ ~you ld expect it to take to sort an array of a half million integers? [6 marks]

Question 2 Write a program which determines which of upper case or lower case words occurs most frequently in a text read from the keyboard, where the text is composed of letters, spaces, and newline characters only. The program should print out all the words of the predominant type in the order in which they occurred in the input. Words of mixed case may occur, but they do not affect the result. For example, if the input consists of

under Dust I lie Sans Wine sans Song sans Singer and SANS END
then the program should output

lower case predominates under lie sans sans and A particular word may occur more than once in the input, with each occurrence counting (and appearing in the output if it is of the predominant type). If both types of word occur equally often, then one of them is arbitrarily chosen.
For maximum credit your solution should make good use of Java's collection classes; a solution using arrays will earn less credit. Structure your solution as a single class with static methods main, isupper, and isLower where isupper is a boolean-valued function which determines whether all the letters in a given a string (passed as a parameter) are upper case, and similarly for islower. [26 marks]

Question 3

You are given the following class for representing dates:


class Date
(

private int day, month, year; / / date in form day, month, year

Date(int day0, int month0, int year0) { / / standard all-arguments constructor

...
1
void put(Data0utputStream out) { / / write date to binary file (at position of file pointer)

void get (DataInputStream in) { / / read date from binary file (at position of file pointer)

void print ( ) { / / print date in form typified by "23/5/2009"

int numyears ( ) { / / return number of complete years elapsed from date to / / today, assuming date precedes today

...

Class D a t e may be freely used in answering the questions that follow. Note that you are not asked to supply the missing code in Date, and you should not do so. (a) Write a class Employee to encapsulate the notion of an employee in a certain company. An employee consists of a name (a single string), a salary (an integer representing euros earned per annum), a grade (one of the upper case letters A to P), and a start date (of type D a t e above, representing the date on which the employee joined the company). The class should have the usual two constructors, i.e. the constructor with no arguments, and the constructor with one argument for each have the following methods: instance variable. It sho~.~ld (i)
put with a parameter of type D a t a o u t p u t s t r e a m to write the employee's attributes to the binary file identified by the parameter, at the position of its file pointer;

(ii)

get with a parameter of type DataInputStream to read the employee's attributes from the binary file identified by the parameter, at the position of its file pointer; print to print employee information in a form typified by "John Smith, Grade C, Started 12/3/1997" issenior to determine if the employee is "senior", by which is meant that he/she has completed at least 5 years with the company, has a salary of at least 30000, and has a grade in the range A to G inclusive. [ I 2 marks]

(iii)

(iv)

Complete the following class which encapsulates the collection of employees in a company, stored in a file:
class Staff
{

private String fileName;

/ / name of file of employees

private void makeFile() { try I Dataoutputstream out = new DataOutputStream(new FileOutputStream(fi1eName)); . . . write employee records [CODE THIS] . . . out.close ( ) ; catch
( IOException

e) { 1 ;

1
void printseniors ( ) . . . [CODE THIS]

.. .

Variable f ileName is the name of a file containing employee records. Method makeFile creates a file with one record for each employee, written using the methods of class Employee in part (a). It suffices to write just one employee record, with the remainder indicated by a comment such as "others similarly". The record written should be for an employee named "John Smith" with annual salary 35000, at grade C, and who joined tlie compaliy on 12/3/1997. Method printseniors prints all the senior employees, each one on a line by itself in a form typified by "John Smith, Grade C, Started 12/3/1997". Note that printseniors must open and close the employee file. [9 marks]

(c)

Write a program consisting of a single class with a main method which tests the preceding classes by creating an employee file called s t a f f . d a t and displaying all the senior employees in the file.

[5 marks]
[End of exam]

T a b l e of Java C l a s s e s (Interfaces in italics) ArrayList<T> ArrayList() ArrayList(Collection<T>) int size() T set(int, T) T get(int) boolean add(T) String tostring() void add(int, T) T remove(int) boolean remove(0bject) boolean contains(0bject) int indexOf(0bject) void clear() boolean isEmpty() boolean addAIl(Collection<T>) boolean retainAll(Collection<?>) boolean removeA11(Collection<?~) boolean containsAII(Collection<?>) Boolean Boolean(boolean) boolean booleanvalue() Calendar static int DAY static int MONTH static int YEAR Character Character(char) char charvalue() static boolean isDigit(char) static boolean isLetter(char) static boolean isLetterOrDigit(char) static boolean isLowerCase(char) static boolean isUpperCase(char) static boolean isWhitespace(char) static char toLowerCase(char) static char toUpperCase(char) Collections static void sort(List<T>) static int binarySearch(List<T>, T) static void shuffle(List<?>) Comparable<T> int compareTo(T) Console static int readInt() static boolean readBoolean0 static double readDouble() static char readchar() static String readstring() static void skipline() static String readToken() static boolean endOfFile() static int available() static boolean hasMoreTokens() static void skipWhitespace() static char peekchar() DataInputStream DataInputStream(File1nputStream) int readInt() throws IOException long readLong0 throws IOException boolean readBoolean0 throws IOException char readchar() throws IOException double readDouble() throws IOException float readFloat() throws IOException String readUTF() throws IOException int read(bytel[]) throws IOException int available() throws IOException void close() throws IOException Dataoutputstream DataOutputStream(File0utputStream) void writeBoolean(boolean) throws IOException void writeInt(int) throws IOException void writeLong(1ong) throws IOException void writeDouble(double) throws IOException void writeFloat(fl0at) throws IOException void writeChars(String) throws IOException void writeL[TF(String) throws IOException void writeChar(int) throws IOException void write(bytel:], int, int) throws IOException void close() throws IOException void flush() throws IOException int size() Double Double(doub1e) double doublevalue(); static double parseDouble(String) static String toString(doub1e) Exception void printStackTrace0 File File(String) boolean exists() boolean isFile() boolean canRead() boolean canwrite() long length() boolean delete() boolean renameTo(Fi1e)

FileInputStream(String) throws FileNotFoundException

FileOutputStream FileOutputStream(String) throws IOException FileOutputStream(String, boolean) throws IOException FileReader FileReader(String) throws FileNotFoundException Filewriter FileWriter(String) throws IOException FileWriter(String, Boolean) throws IOException Float Float(float) float floatvalue(); static float parseFloat(String) static String toString(float) GregorianCalendar GregorianCalendarO int get(int) HashMap<T,U>
HashMap() HashMap(Map<T,U>) void clear() U put(T key, U value) U get(0bject key) U remove(0bject key) boolean containsKey(0bject key) int size() boolean isEmpty() Set<T> keyset() String tostring()

T getlast() T removeFirst() other methods as ArrayList<T>

Long Long(long) long longvalue() static long parseLong(String) static String toString(1ong) Math static double random() static double abs(double) static int abs(int) etcetera static double ceil(doub1e) static double floor(doub1e) static int max(int, int) etc. static int min(int, int) etc. static double rint(doub1e) static long round(doub1e) static int round(float) static double sqrt(doub1e) Object boolean equals(0bject) String tostring() PrintWriter PrintWriter(String) PrintWriter(Fi1eWriter) PrintWriter(FileWriter, boolean) void print(String) void println(String) void println() PrintWriter printf(String, Object ...) void close() void flush() Random AccessFile RandomAccessFile(String, String) throws IOException long length() throws IOException void seek(long) throws IOException int readlnt() throws IOException long readLong0 throws IOException boolean readsoolean() throws IOException char readchar() throws IOException double readDouble() throws IOException float readFloat() throws IOException String readUTF() throws IOException void writeBoolean(boolean) throws IOException void writeInt(int) throws IOException void writeLong(1ong) throws IOException void writeDouble(doub1e) throws IOException void writeFloat(float) throws IOException void writeChars(String) throws IOException void writeUTF(String) throws IOException void writeChar(int) throws IOException void close() throws IOException

HashSet<T> Hashset() HashSet(ColIection<T>) boolean add(T) boolean remove(T) boolean contains(T) int size() void clear() boolean isEmpty() boolean addAII(Collection<T>) boolean retainAll(Collection<?>) boolean removeA11(Collection<?>) boolean containsA11(Collection<?>) Integer Integer(int) int intValue() static int parseInt(String) static String toString(int) LinkedList<T> LinkedListO LinkedList(Collection<T>) void addFirst(T) T getFirst()

Scanner Scanner(File) throws FileNotFoundException Scanner(String) String nextline() String next() int nextlnt() long nextLong0 double nextDouble() boolean nextBoolean() boolean hasNextLine() boolean hasNext() boolean hasNextlnt() boolean hasNextLong() boolean hasNextDouble() boolean hasNextBoolean() void close() String int length() boolean startsWith(String) boolean endsWith(String) int indexOf(String) String substring(int, int) String substring(int) char charAt(int) String touppercase() String toLowerCase() String trim() static String valueOf(int) static String valueOf(1ong) static String valueOf(double) static String valueOf(float) static String valueOf(boolean) static String valueOf(char) static String valueOf(char[], int, int) static String valueOf(charl~1) boolean equalslgnoreCase(String) void getChars(int, int, char[], int) System static long currentTimeMillis() static long nanoTime() static void exit(int) TreeSet<T> Treeset() TreeSet (Co\lection<T>) methods as HashSet<T> TreeMa p<T,U> TreeMap() TreeMap(Map<T,U>) methods as HashMap<T,U>

You might also like