comp6700 introductory programming introductory ... to type your answers in ~/final-exam/q?/q?.txt...

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

Upload: trinhtram

Post on 08-Apr-2018

218 views

Category:

Documents


1 download

TRANSCRIPT

THE AUSTRALIAN NATIONAL UNIVERSITY

First Semester 2016 — Final Examination

COMP6700Introductory 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 todo 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 devicewith 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 athttp://docs.oracle.com/javase/8/docs/api/index.html

• A full set of JavaFX API documentation is available athttp://docs.oracle.com/javase/8/javafx/api/toc.htm

• A Reference Card “Core Java” (from the dzone.com) by Cay Hortsmann and IvanSt. Ivanov; the link to this pdf-document is on your computer desktop (just likethe Examination Paper)

As a convenience, a tab is made available on the toolbar of your web browser for eachof 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 isprobably 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 filesyou 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 thebest 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 toask 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 anyother you may prefer. Do not use LibreOffice program as it does not save files inplain 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!

COMP6700 (Introductory Programming) Page 2 of 16

QUESTION 1 [30 marks]The answers to this question are to be typed in the file q1.txt in the ~/final-exam/q1directory. 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 programstructures, 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 beorganised?

7. Explain the difference between the statements "break;" and "continue;" whenthey are executed inside a loop.

8. Where in a Java program can one use the "return;" statement? What effect doesit 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 readsidentically 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, whichmay 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

COMP6700 (Introductory Programming) Page 3 of 16

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 bededucted — 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 thato1 == 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 VirtualMachine (JVM) looks for when the application classes are loaded, and the applicationitself needs to be launched. The mainmethod must have an exactly specified signature.Consider the following source code:

StringyThing.java1

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 }

COMP6700 (Introductory Programming) Page 4 of 16

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 separateparagraphs. Mark every answer accordingly as Q1.a, Q1.b etc.

COMP6700 (Introductory Programming) Page 5 of 16

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.javawhich 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 thetask. 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 programcalled “WordSearch” which will open and read a text file (written in English) with the aimof 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 taskis to be achieved by creating a single class Java program WordSearch.java, which canbe compiled and run with a command-line arguments representing the file name and thekeyword 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 barSearch file foo.txt for keyword barbar 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 breakinghere).

Go to the directory q2 and find a sample text file called stapledon_FLM.txt (which containsthe 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 whichcontain, for example, the word “Neptune”:

> java WordSearch stapledon_FLM.txt neptuneSearch file stapledon_FLM.txt for keyword neptuneneptune 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,

COMP6700 (Introductory Programming) Page 6 of 16

This question has two parts:

(a) The first step (task) is to write WordSearch.java that will correctly spot all wordswhich 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 identicaloutputs:

> java WordSearch stapledon_FLM.txt CapoSearch file stapledon_FLM.txt for keyword CapoCapo has been found on lines: 9689,> java WordSearch stapledon_FLM.txt capoSearch file stapledon_FLM.txt for keyword capocapo has been found on lines: 9689,

That is, the comparison of the keyword and a word from the text is performed withignoring the case of characters. “Exactly” means that the keyword must match a propergrammatical 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 ofthe word “woman”:

> java WordSearch stapledon_FLM.txt englishwomanSearch file stapledon_FLM.txt for keyword englishwomanenglishwoman has been found on lines: 444, 448,> java WordSearch stapledon_FLM.txt womanSearch file stapledon_FLM.txt for keyword womanwoman 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 shouldcheck if the necessary command-line arguments are provided. If args.length value issmaller than 2, the program should report that there are errors and supply the correctusage and exit. If a text file cannot be read, the result also should be prematuretermination. 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 canbe one line even it is long (there is no need to format it); you can also retain the lastcomma (which follows the last line with the key word), like it is shown in the examplesabove.

[12 marks]

(b) In this part (second task), you will consider punctuation. Your code of WordSearch.javafrom 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 whitespace character). This corresponds naturally to the grammatical separation of words

COMP6700 (Introductory Programming) Page 7 of 16

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 willfail 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, againstwhich 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 theoccurrence words are followed by a comma, or a full-stop, or any other punctuationsymbol.

Note: you can choose to write this improved version of your program WordSearch.javain place of the previous version. If this version of the program is correct, your first taskwill 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 byline. 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 thefile contents to process it with a pipeline (however, you will not loose any marks if yourprogram 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 firstargument 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 inputstream) and a string (keyword), and performs the search and printout. You can invoke thismethod from main(). Use of such a helper method can keep the “normal” code (inside thetry-block) short and simple.

Note: If you are using the NIO.2 stream based approach, a different helper method can bedefined to operate on a string (representing a line of text), when called inside the streamoperations 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 Javaprogram.

COMP6700 (Introductory Programming) Page 8 of 16

QUESTION 3 [30 marks]The answers to this question are to be typed in the file q3.txt in the ~/final-exam/q3directory.

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 characteristicsof 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 whichyou have identified in the first point above? Give a simple example (eg, using afactorial 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 apredicate (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 necessaryfields and methods in its interface to make the above statement correct).

COMP6700 (Introductory Programming) Page 9 of 16

Rewrite the above statement using a ��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, theyalso 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; andjava.util.stream.Collectors.toListmethods which we can statically import intoour program. By using these methods, rewrite the above three loops as a single streampipeline.

[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 theprogram execution which allows multiple branches, the exception techniques isnot very convenient for programming in a functional style, when a return valuefrom one function can be used as an input for another. What is an alternative todefining a method which has only one output channel, no matter if the correct

COMP6700 (Introductory Programming) Page 10 of 16

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 thosechallenges.

[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 separateparagraphs. Mark every answer accordingly as Q3.a, Q3.b etc.

COMP6700 (Introductory Programming) Page 11 of 16

QUESTION 4 [20 marks]

Practical Exam Question

Complete a simple computer program which uses lambdas, streams and the JavaFXlibrary.

Approximate time: 50–60 min.

The purpose of this question is to test your ability to quickly read and understand the codeof a fairly small Java program using the help of Java’s API documentation. The programstudy 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 applicationcalled 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 playthe rôle of gates that hold the balls up on the high level, and should open to allow them tofall). The code deliberately uses the language features which have been introduced in Java8 SE. Read and understand this program.

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

Task 1 is to make the program open each gate when a corresponding key-pressed event isdetected (low case letters R, G and B). Once a gate is open, it should stay open even ifthe 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 theoriginal code) cycles. Note that, all the necessary timeline objects are already definedand 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 loosea fraction of their kinetic energy when they bounce off the bottom; since the kineticenergy (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 towhich the balls bounce in each cycle; when the maximum height becomes smallerthan one pixel, one can stop the motion. Details of implementing the damping effectare 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.

COMP6700 (Introductory Programming) Page 12 of 16

(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 yourDesktop and watch a one-minute video.

You can use an IDE of your choice to work on this question, but to quickly compile and runthe program, you can choose to use the provided Makefile (in the directory q4, alongsidewith the original source code, in q4/src directory):

% make compilejavac -d bin src/balls/Balls.java% make run

COMP6700 (Introductory Programming) Page 13 of 16

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 ofapplication 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 andtheir motion is periodic. The timeline objects, which are already defined, only carryout the animation for 25 cycles. The suggested location for adding code in the originalfile is:

Balls.java: 167

[6 marks]

(c) Modify the code which define the falling ball timeline by changing the key frameswhich are gradually inserted in the timeline to account for reduction in the verticaldistance (the height) to which balls fly and fall back after every bounce. The dampingparameter (dampingFactor) is already defined, you need to make the correct useof 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 theheight value becomes smaller than a pixel, this should provide the loop exit. Thesuggested 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 thelocation of the TODO markers, you can user the grep command-line utility (assuming youare 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).

COMP6700 (Introductory Programming) Page 14 of 16

You are free to use an IDE (Eclipse, Netbeans, or IntelliJ IDEA CE), but this is not essentialsince the missing code is not supposed to contain too many calls to the large JavaFX API. TheJavaFX API documentation is available. You can do well without using an IDE, but insteadusing an editor and the already mentioned Make utility.

Remark 1: The amount of additional code (for all tasks) is very small (not more than 15lines); and the use of JavaFX API classes is very basic, similar to how it is already used inthe 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 threequestions before attempting this one. Any incomplete but sensible attempt will be rewardedwith 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 youranswer. If you used an IDE and created a project somewhere in the your file system, at theend, please move or copy the final version of source files to the same directory where youfound the original code: ~/final-exam/q4/src. As an option, you should consider writinga text file, q4.txt, which explains what you were able to achieve in this question.

COMP6700 (Introductory Programming) Page 15 of 16

Checklist:

Before you leave the exam, make sure that all your answers are in the right files in the rightlocations.

• Your answer to Question 1 must be in the plain text file q1.txt saved in the directoryq1. 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 calledWordSearch.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 directoryq3. Number answers to the sub-questions accordingly (as it is done in the Question1).

• Your solutions to Question 4 must be saved in the Java source file Balls.java inthe 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.

COMP6700 (Introductory Programming) Page 16 of 16