0% found this document useful (0 votes)
86 views

Final Exam2016

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Final Exam2016

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

THE AUSTRALIAN NATIONAL UNIVERSITY

First Semester 2016 — FINAL EXAMINATION

COMP6700
Introductory Programming

Writing Period: 3 hours


Study Period: 15
minutes
Permitted MATERIALS: An A4 sheet with notes on both sides

1. Marks for each question are indicated on the exam paper.

2. Answer all questions by creating or modifying files on the computer system as in-
structed. Do not move or rename files unless explicitly told to do so in the
instructions.

3. During the exam you may not communicate with anyone, in any way. Any attempt
to do so will be dealt with under the rules for Misconduct in Examinations.

4. Leave all mobile or smart phones, PDAs, MP3 players, Google Glass or any other
device with network communication and data storage functionality in your bag at
the door.

5. You may not use the printers, CD-ROM drive or USB flash drives.

6. You must sit at the machine allocated to you.

7. Return this paper when you leave the examination room.

COMP6700 (Introductory Programming) Page 1 of 16


Advice

1. You are allowed to use the following documentation:

• A full set of JAVA API documentations is available at


http://docs.oracle.com/javase/8/docs/api/index.html
• A full set of JAVAFX API documentation is available at
http://docs.oracle.com/javase/8/javafx/api/toc.htm
• A Reference Card “Core Java” (from the dzone.com) by Cay Hortsmann and
Ivan St. Ivanov; the link to this pdf-document is on your computer desktop
(just like the Examination Paper)

As a convenience, a tab is made available on the toolbar of your web browser for
each of the above URLs.

2. Each question has an approximate timing estimate. These estimates are a guide
only. Be careful not get stuck on particular questions which may yield a small mark.
It is probably a good idea to do the easiest parts first.

3. If you mess up something and want to start anew, there is a local copy of all the files
you were given at /courses directory (mind the root /).

4. Fractional marks are possible for all questions. Just because the requirements say
“must” does not mean you’ve failed if your program doesn’t do precisely that. Do
the best you can, and don’t panic.

5. Your answers and the source code must be typed in files named and located in accor-
dance with instructions given in each question. The exam directory is called ~/final-
exam/ (~ is your home directory). If not sure where to save your files — do not
hesitate to
ask for clarification.

6. To type your answers in ~/final-exam/q?/q?.txt files (the question mark symbol


? here stands for 1, or 2, or 3, or 4), use a PLAIN text editor, like Atom or Gedit, or any
other you may prefer. Do not use LibreOffice program as it does not save files in
plain text format.

7. To write a program code, use either an editor, or an IDE (IntelliJ IDEA, Eclipse or
Net- beans), but do save the source code files in the corresponding directory as
instructed (see ends of Q2 and Q4 for instructions).

8. Good Luck!
QUESTION 1 [30 marks]
The answers to this question are to be typed in the file q1.txt in the ~/final-exam/q1
directory. Put the answer for each part in a separate paragraph and delineate them as
Q1.a, Q1.b, etc.
Approximate time: 35–45 min.

(a) This question contains parts, all related to the structural knowledge of a program.

1. The control structures in a computer program can be characterised as


sequence, CONDITIONAL, AND ITERATION. From what is known to you about Java’s
program structures, give examples of sequence and iteration.
2. What is an alternative to a switch statement?
3. Can you define a method inside another method in Java?
4. Can you define a class inside another class in Java?
5. Can you define a class inside a method in Java?
6. What are three different layers in which a (potentially large) program can be
organised?
7. Explain the difference between the statements "break;" and "continue;"
when they are executed inside a loop.
8. Where in a Java program can one use the "return;" statement? What effect
does it have of the flow of control? (Note: the return statement has no
argument.)

[8 marks]

(b) The following method was written to determine whether its String parameter reads
identically left-to-right and right-to-left (the so called palindrome).

boolean isPalindrome(String s)
{ int i = 0, j = s.length() -
1;
while (i != j && s.charAt(i) == s.charAt(j)) { i+
+;
j--;
}
return (i == j);
}

This method compiles fine, yet unfortunately, the code contains a logic error, which
may result in a run-time error, or wrong output.

1. Find the error and explain what problem it will cause 2 marks
2. Fix the error (write the correct statements) 3 marks
3. Write an alternative, recursive implementation 6 marks

[11 marks]

(c) Which of the following statements about object-oriented properties of Java are true
(each correct answer is worth of 1 mark, for each wrong answer 0.5 marks will be
deducted — tread carefully and leave questions unanswered if not sure):

1. One can define own primitive type, and own reference type in Java.
2. Given that o1 and o2 are two declared and initialised references to objects of
the same class, the true value of the expression o1.equals(o2) always
implies that o1 == o2 also evaluates to true.
3. An abstract class can extend a non-abstract (concrete) class.
4. When overriding a method whose return value has the type of the parent class,
one can change the return type to match the subclass type.
5. An enum type definition can include a public constructor.
6. An interface can extend a class.
7. An abstract class can implement an interface.

[7 marks]

(d) The main method plays a special rôle in Java. It is this method that the Java Virtual
Machine (JVM) looks for when the application classes are loaded, and the
application itself needs to be launched. The main method must have an exactly
specified signature. Consider the following source code:

StringyThing.java
1

2 public class StringyThing {


3 public static void main(String[] args) {
4 String s = new String("Hello world");
5 System.out.println(s);
6 }
7 }
8

9 class String {
10 private final java.lang.String s;
11

12 public String(java.lang.String s)
13 { this.s = s;
14 }
15 public java.lang.String toString()
16 { return s;
17 }
18 }
This code compiles, but when run, the following error message is emitted

Exception in thread "main" java.lang.NoSuchMethodError: main

which seems paradoxical since the main method is right there!

Explain why the JVM interpreter is, nevertheless,


right.
[4 marks]

Important: Your solutions to the Question 1 must be in a single plain text file, q1.txt,
in the ~/final-exam/q1 directory. Type in the answers to the different parts in separate
paragraphs. Mark every answer accordingly as Q1.a, Q1.b etc.
QUESTION 2 [20 marks]
Practical Exam Question
The answers to this question in the form of source code are to be typed in the file
WordSearch.java which must be saved in the ~/final-exam/q2 directory.

You can OPTIONALLY include the file q2.txt to describe how you have tried to accomplish
the task. This is useful for the examiners if, for some reason, you do not complete the
program.
Approximate time: 55-60 min.
As specified in parts (a) and (b), your overall task in this question is to write a Java
program called “WordSearch” which will open and read a text file (written in English)
with the aim of finding all lines which contain one or more occurrences of a given
keyword. The line numbers where the word is found found will be printed to the standard
output. This task is to be achieved by creating a single class Java program
WordSearch.java, which can be compiled and run with a command-line arguments
representing the file name and the keyword as follows:

> java WordSearch filename keyword

The program will read the file and find all lines where the keyword is present. For example:

> java WordSearch foo.txt bar


Search file foo.txt for keyword bar
bar has been found on lines: 2, 9, 11, 13, 15, 20, 24, 29, 30, 31, 42, 46, 52,
59, 60, 68, 77, 79, 83, 85, 87, 90, 95, 96, 98, 103, 104, 105, 109, 112, 115,
117, 119, 121, 125, 129, 134, 140, 143, 152, 154, 155, 156, 162, 166, 187, 224,
227, 235,

(all the line numbers are printed on one line, so there is no need to program the line
breaking here).
Go to the directory q2 and find a sample text file called stapledon_FLM.txt (which
contains the text of “Last and First Men. A Story of the Near and far Future” by W. Olaf
Stapledon, one of the texts we used in Assignment One). When your program is
successfully completed, compiled and debugged, it can be used on the above file for
searching all the lines which contain, for example, the word “Neptune”:

> java WordSearch stapledon_FLM.txt neptune


Search file stapledon_FLM.txt for keyword neptune
neptune has been found on lines: 9540, 9541, 9546, 9547, 9557, 9570, 9574,
9576, 9586, 9590, 9602, 9614, 9666, 9674, 9682, 9693, 9701, 9712, 9734, 9739,
9747, 9765, 9771, 9842, 9858, 9898, 10082, 10100, 10105, 10108, 10116, 10144,
10605, 10609, 10646,
This question has two parts:

(a) The first step (task) is to write WordSearch.java that will correctly spot all words
which EXACTLY match the keyword but REGARDLESS of the CASE but ignoring
PUNCTUATION. “Regardless of the case” means that the keywords CAPO and CAPO will
produce identical outputs:

> java WordSearch stapledon_FLM.txt Capo


Search file stapledon_FLM.txt for keyword Capo
Capo has been found on lines: 9689,
> java WordSearch stapledon_FLM.txt capo
Search file stapledon_FLM.txt for keyword capo
capo has been found on lines: 9689,

That is, the comparison of the keyword and a word from the text is performed with
ignoring the case of characters. “Exactly” means that the keyword must match a
proper grammatical word, but not a substring in a word of text. For example: the
word “englishwoman” occurs only twice in the text, while there are multiple
occurrences of the word “woman”:

> java WordSearch stapledon_FLM.txt englishwoman


Search file stapledon_FLM.txt for keyword englishwoman
englishwoman has been found on lines: 444, 448,
> java WordSearch stapledon_FLM.txt woman
Search file stapledon_FLM.txt for keyword woman
woman has been found on lines: 1754, 2064, 2150, 2159, 2183, 2194,
2298, 2317, 2325, 2326, 2775, 2905, 4033, 4080, 4123, 4281, 5881,
6799, 7068, 7085, 7086, 7087, 8361, 10710,

Note: You will be writing this program from scratch. At the start, your program
should check if the necessary command-line arguments are provided. If
args.length value is smaller than 2, the program should report that there are
errors and supply the correct usage and exit. If a text file cannot be read, the result
also should be premature termination. Naturally, these sort of actions are best
programmed using exceptions. The output which contains the list of line numbers
where the key word is found can be one line even it is long (there is no need to
format it); you can also retain the last comma (which follows the last line with the
key word), like it is shown in the examples above.
[12 marks]

(b) In this part (second task), you will consider punctuation. Your code of
WordSearch.java from the previous task MAY employ the String.split() method
and/or Scanner.next() method with the default setting of the delimiter (an arbitrary
sequence of the white space character). This corresponds naturally to the grammatical
separation of words
in a sentence. But this naïve setsup fails when the punctuation symbols are
included. When breaking a sentence is done against the white spaces only, one can
get “Mars.” and “Mars,” as different words alongside with “Mars”. The naïve word
matching will fail to detect the first two cases if the search is performed with the
keyword “Mars”. Your task in this part is to improve your program, such that words
in a text, against which the keyword is matched, are made of characters and
numbers only. The exam- ple above prints out all the lines containing the keyword
“neptune” regardless if the occurrence words are followed by a comma, or a full-
stop, or any other punctuation symbol.
Note: you can choose to write this improved version of your program WordSearch.java
in PLACE of the previous version. If this version of the program is correct, your first task
will be acknowledged as correctly done.
[8 marks]

Advice:
1. Start with creating the program skeleton — get it to open and read the text file line by
line. Use of the java.util.Scanner is the most appropriate and simple choice. Even
better (simpler and faster to program) might be to use the Java java.nio library and
STREAM the file contents to process it with a pipeline (however, you will not loose any
marks if your program is written with the use of the plain old java.io, provided it
operates correctly).
Make sure that the program reacts on the absence of necessary command line arguments,
and on the absence or unreadability of the text file whose name is represented by the first
argument by reporting errors as explained at the end of task (a) description.
2. It is useful to define a helper method which takes two arguments, a scanner (or an
input stream) and a string (keyword), and performs the search and printout. You can
invoke this method from main(). Use of such a helper method can keep the “normal”
code (inside the try-block) short and simple.
Note: If you are using the NIO.2 stream based approach, a different helper method can
be defined to operate on a string (representing a line of text), when called inside the
stream operations filter, or forEach, or reduce.

Important: Your solutions to Question 2 must be in the file WordSearch.java, in the


~/final-exam/q2 directory. The source code must be a compilable and executable Java
program.
QUESTION 3 [30 marks]
The answers to this question are to be typed in the file q3.txt in the ~/final-exam/q3
directory.
Approximate time: 40–45 min.

(a) Computational problems can be characterised QUALITATIVELY as

• Easy
• Tractable
• Hard

Give at least two examples in each category, and provide QUANTITATIVE characteristics
of their difficulty using the O -notation (“order of” notation).
[6 marks]

(b) Answer the following questions about recursive methods and algorithms:

• What is the major thing that limits the use of recursively defined methods?
2 marks
• What is “tail-call” recursion? 2 marks
• How can tail-call recursion be modified to remove the major limitation which
you have identified in the first point above? Give a simple example (eg, using a
factorial function) 4 marks
• Does Java allow such tail-recursion modification (optimisation)? 2 marks

[10 marks]

(c) Consider the following statement which defines a value of an object whose type is a
predicate (java.util.function.Predicate):

Predicate<CrewMember> youngOrImportant = new Predicate<CrewMember>


{ public boolean test(CrewMember m) {
boolean young = m.getAge() < 21;
boolean valuable = m.status.value() > 50;
return young || valuable;
}
}

(assume that the class CrewMember is defined elsewhere, and that it has all necessary
fields and methods in its interface to make the above statement correct).
Rewrite the above statement using a 2— expression instead of an instance of the
anony- mous inner class on the right-hand side.
[3 marks]

(d) Among other advantages which streams have over standard container objects, they
also provide the possibility of shorter and more expressive coding. Consider the fol-
lowing program snippets which are written in the olde (pre-Java 8) style

List<Book> booksForGoogleToScan = new ArrayList<>();


for(Book b: allBooksInTheWorld){
if(b.copyRightExpired() || b.permissionToScanExtorted())
{ booksForGoogleToScan.add(b);
}
}

Collections.sort(booksForGoogleToScan, new Comparator<Book>() {


public int compare(Book b1, Book b2) {
return b1.getISBN() - b2.getISBN();
}
});

List<Integer> isbnOfBooksToScan = new ArrayList<>();


for(Book b: booksForGoogleToScan){
isbnOfBooksToScan.add(b.getISBN());
}

In Java 8’s extended API, we now have the java.util.Comparator.comparing;


and java.util.stream.Collectors.toList methods which we can statically
import into our program. By using these methods, rewrite the above three loops as
a single stream pipeline.
[4 marks]

(e) This question has two parts which deal with exceptions and their alternatives for
han- dling a computation which does not provide a correct result.

• What are three benefits which exceptions bring to Object-Oriented Program-


ming? 3 marks
• Because a method which can throw an exception defines a flow of control in
the program execution which allows multiple branches, the exception
techniques is not very convenient for programming in a functional style, when
a return value from one function can be used as an input for another. What is
an alternative to defining a method which has only one output channel, no
matter if the correct
value can or cannot be returned? (Simply name the approach without elaborat-
ing.)
1 mark

[4 marks]

(f) Kunshan Wang, in his guest lecture, talked about three MAJOR CHALLENGES which
imple- menters of modern programming languages face. Name and briefly describe
those challenges.
[3 marks]

Important: Your solutions to the Question 3 must be in a single plain text file, q3.txt,
in the ~/final-exam/q3 directory. Type in the answers to the different parts in separate
paragraphs. Mark every answer accordingly as Q3.a, Q3.b etc.
QUESTION 4 [20 marks]
Practical Exam Question
Complete a simple computer program which uses lambdas, streams and the JAVAFX
library.
Approximate time: 50–60 min.
The purpose of this question is to test your ability to quickly read and understand the
code of a fairly small Java program using the help of Java’s API documentation. The
program study is necessary for adding code to make the program attain the required
functionality.
Go to the q4 directory, where you will find the Java source code for a JavaFX
application called balls. This is a small program, which consists of only one class BALLS. It
is a JAVAFX application. It creates a simple scene with three coloured balls, three rectangles
(which play the rôle of gates that hold the balls up on the high level, and should open to
allow them to fall). The code deliberately uses the language features which have been
introduced in Java 8 SE. Read and understand this program.

As specified in parts (a) — (c) below, you will need to write three small extensions of the
program to make it complete:

Task 1 is to make the program open each gate when a corresponding key-pressed event is
detected (low case letters R, G and B). Once a gate is open, it should stay open even
if the user presses the same key again (part (a) below);

Task 2 is to make a ball, under which the gate has been opened, start falling down imme-
diately, bounce off the bottom and continue this periodic motion for a few (25, in
the original code) cycles. Note that, all the necessary timeline objects are already
defined and set up — you only need to use them (part (b) below);

Task 3 is to make the bouncing motion for each ball more realistic: The balls must loose
a fraction of their kinetic energy when they bounce off the bottom; since the kinetic
energy (energy of motion) at the bottom converts into the potential energy at the top
(when the balls reach the highest point and become motionless before starting to
fall), the effect of DAMPING should result in a gradual decrease in the maximum
height to which the balls bounce in each cycle; when the maximum height
becomes smaller than one pixel, one can stop the motion. Details of implementing
the damping effect are up to you (part (c) below).

Taken at different steps of implementations (original, Task 1, Tasks 1 and 2, and fully im-
plemented), the program behaviour can be illustrated as in the Figure.
(Top Left) Neither gates nor balls move when a key-pressed event is detected — the original pro- gram; ( Top Right) the gates
open and stay open when key-pressed events are detected (but the balls remain motionless — the Task 1 implemented);
(Bottom Left) the balls fall and bounce “in- definitely” when the Task 2 is implemented; (Bottom Right) the balls’ motion is
dampened by the energy loss at every bounce, and the gradually comes to rest at the bottom.

To observe the behaviour of completed balls program, open the file q4.balls.webm on
your Desktop and watch a one-minute video.
You can use an IDE of your choice to work on this question, but to quickly compile and
run the program, you can choose to use the provided Makefile (in the directory q4,
alongside with the original source code, in q4/src directory):

% make compile
javac -d bin src/balls/Balls.java
% make run
You have three tasks:

(a) Add to the callback code for the key-pressed event handler to make the gates open
(by using the ROTATE transform). Once open, the gate should stay open for the rest
of application run. The suggested location for adding code in the original file is:

Balls.java: 162

[6 marks]

(b) Add more to the callback code for the key-pressed event handler to make the balls
fall. At this point, the balls can fall and bounce forever since they do not lose energy
and their motion is periodic. The timeline objects, which are ALREADY defined, only
carry out the animation for 25 cycles. The suggested location for adding code in the
original file is:

Balls.java: 167

[6 marks]

(c) Modify the code which define the falling ball timeline by changing the key frames
which are gradually inserted in the timeline to account for reduction in the vertical
distance (the height) to which balls fly and fall back after every bounce. The
damping parameter (dampingFactor) is already defined, you need to make the
correct use of it. Since you cannot know in advance how many times the balls will
bounce off, you need to replace the for-loop in the original code onto the while-
loop; when the height value becomes smaller than a pixel, this should provide the
loop exit. The suggested location for ADDING AND CHANGING code in the original file
is:

Balls.java: 137-148

[8 marks]

If you changed the original code already, the above lines may be perturbed; to find the
location of the TODO markers, you can user the grep command-line utility (assuming you
are in the q4 directory):

% grep -n TODO src/*.java


// TODO 3: change for-loop for while-loop and make changes in the
// TODO 1: add more code to complete Task 1
// TODO 2: add more code to complete Task 2

(or you can use the Search feature of your IDE).


You are free to use an IDE (Eclipse, NETBEANS, or IntelliJ IDEA CE), but this is not essential
since the missing code is not supposed to contain too many calls to the large JAVAFX API.
The JavaFX API documentation is available. You can do well without using an IDE, but
instead using an editor and the already mentioned Make utility.
Remark 1: The amount of additional code (for ALL tasks) is very small (not more than 15
lines); and the use of JavaFX API classes is very basic, similar to how it is already used in
the starting code. Understanding the original program is most important.
Remark 2: Do not get too nervous about this Question. Perhaps, try to finish the first
three questions before attempting this one. Any incomplete but sensible attempt will be
rewarded with partial marks.

Important: Your solutions to Question 4 must be in the Java source files in the directory
~/final-exam/q4/src. The original code should be modified accordingly to represent
your answer. If you used an IDE and created a project somewhere in the your file system,
at the end, please move or copy the final version of source files to the same directory
where you found the original code: ~/final-exam/q4/src. As an option, you should
consider writing a text file, q4.txt, which explains what you were able to achieve in this
question.
Checklist:
Before you leave the exam, make sure that all your answers are in the right files in the
right locations.

• Your answer to Question 1 must be in the plain text file q1.txt saved in the directory
q1. Number answers to the sub-questions accordingly, for example

My answers to the Question 1.


=============================

Q1.a

Blah-blah-blah...

Q1.b

Gobbledegook-gobbledegook-gobbledegook...
... ... ...
... ... ...

• Your answers to Question 2 must be the source code of a completed program called
WordSearch.java, saved in the directory ~/final-exam/q2.

• Your answer to Question 3 must be in the plain text file q3.txt saved in the
directory q3. Number answers to the sub-questions accordingly (as it is done in the
Question 1).

• Your solutions to Question 4 must be saved in the Java source file Balls.java in
the directory ~/final-exam/q4/src. The original code should be modified accord-
ingly to represent your answer. As an option, you should consider writing a text file,
~/final-exam/q4/q4.txt, which explains what you were able to achieve in this
ques- tion if for some reason you are unable to produce a working solution.

You might also like