Mock Exam 2023.pdf
Document Details
University of KwaZulu-Natal
2023
Tags
Full Transcript
SCHOOL OF MATHEMATICS, STATISTICS & COMPUTER SCIENCE MOCK EXAM NOVEMBER 2023 COMP102WP2: Computer Programming DURATION: 3 hours TOTAL MARKS: 100 INTERNAL EXAMINERS: S...
SCHOOL OF MATHEMATICS, STATISTICS & COMPUTER SCIENCE MOCK EXAM NOVEMBER 2023 COMP102WP2: Computer Programming DURATION: 3 hours TOTAL MARKS: 100 INTERNAL EXAMINERS: S.Z. Dlamini & M. Mngomezulu EXTERNAL EXAMINER: R. Els INSTRUCTIONS 1. This paper consists of 13 pages (incl. this one). 2. Pages 11–13 contain reference material that you may find useful. 3. Answer all questions. 4. Start the answers to each question on a new page. 5. You may answer the programming questions in pencil. 6. The use of a calculator is NOT allowed. 7. Code that is unreadable or difficult to read will be penalised. UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 QUESTION ONE: TRACING [15 marks] Give the output produced by each of the following code snippets. If there is no output due to a compile-time or run-time error, then state and explain the error. 1.1. class Q1 { (3) public static void main(String[] args) { int a; int b; a = 10; if(a != 10 && a / 0 == 0) { System.out.println(b); } else { System.out.println(++b); } } } 1.2. class Numbers { (3) private int a; private int b; Numbers() { this(50); System.out.print(50 + " "); } public Numbers(int y) { this(5, 4); System.out.print(100 * 4 + " "); } public Numbers(int a, int b) { this.a = a; this.b = b; System.out.print(a + b + " "); } public int getA() { return a; } public int getB() { return b; } } class TestNumbers { public static void main(String[] args) { Numbers questionTwo = new Numbers(80); System.out.print(questionTwo.getA() + " " + questionTwo.getB()); } } 2 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 1.3. class Item { (3) private String colour = "red"; public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } } class TestItem { public static void main(String[] args) { Item itemOne = Item(); Item itemTwo = Item(); itemOne.setColour("blue"); itemTwo = itemOne; itemTwo.setColour("red"); System.out.println(itemOne.getColour() + " " + itemTwo.getColour()); } } 1.4. class Q4 { (3) public static void main(String[] args) { String one = "hello"; String two = new String("hello"); String three = "hello"; if(one == two) { System.out.println("one and two are equal"); } else { System.out.println("one and two are not equal"); } if(one == three) { System.out.println("one and three are equal"); } else { System.out.println("one and three are not equal"); } } } 3 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 1.5. class Q5 { (3) public static void main(String[] args) { String five = new String("5"); System.out.println(1 + 10 + five + 1 + 10); } } QUESTION TWO: STRINGS I [10 marks] Write a method: public static String getLongestPrefix(String[] strings) that will find and return the longest prefix substring from an array of strings. For example, given an array of the following strings “flower”, “flow”, and “flight”; the method would return “fl”. Given the strings “dog”, “racer”, and “car”; the method will return an empty string. QUESTION THREE: ARRAYS I [10 marks] Write a method: public static void showLeaders(int[] array) that displays all of the elements that are “leaders” in an array. An element is considered a leader if there is no element greater than it on the right side of it in the array. For example: For array [16, 17, 4, 3, 5, 2], the leaders are 17, 5, and 2 In the array [12, 9, 7, 14, 8, 6], the leaders are 14 and 6 QUESTION FOUR: ARRAYS II [10 marks] Write a method: public static void showTriangle(int rows) that displays a number triangle like the one shown below. The method receives an integer indicating the number of rows the triangle should have. The number of rows also determines the number of columns that the triangle has. The triangle below was created with a rows value of 5. 4 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 QUESTION FIVE: UKZN BANK [25 marks] UKZN has established a bank to be used by students and staff at the University. They want to perform analytics on the transactions being done by their clients, especially transfers from one client to another. They have given you access to a text file that contains 250 transfers and want you to complete a small Java program to analyse these transfers. Each one of the 250 lines in the transfers.txt text file contains a sender account number, a recipient account number, the amount sent, and the date of the transaction. Each piece of data is separated by a semi-colon (;). A snippet of the contents of the file is shown below: 4389767090;2573919515;7729.02;2023-11-27 4262763389;2362740981;26720.41;2023-10-28 4856174833;3016491397;22080.37;2023-2-28 1769416549;5194517042;30062.86;2022-11-20 A class to represent a Transfer has been created and is shown below: import java.time.LocalDate; class Transfer { private String sender; private String recipient; private LocalDate date; private double amount; public Transfer(String sender,String recipient, LocalDate date, double amount) { this.sender = sender; this.recipient = recipient; this.date = date; this.amount = amount; } public String getSender() { return sender; } public String getRecepient() { 5 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 return recipient; } public LocalDate getDate() { return date; } public double getAmount() { return amount; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(date); sb.append(" [" + sender + "] => "); sb.append("[" + recipient + "] "); sb.append(": R" + amount); return sb.toString(); } } Your program has another class called TransfersAnalyser.java. The main method reads in the information in the text file called transfers.txt and stores than in an array called transfers. Complete the following two methods, which are located in the TransfersAnalyser class. 5.1. A method (10) public static void searchTransfers(Transfer[] transfers, int month, double greaterThan) that receives as arguments the array of transfers, an integer indicating the month of the year and value of money. The method must display all transfers made in a particular month whose value is greater than the amount given as the third argument to the method. 5.2. A method (15) public static void selfishOrGenerous(Transfer[] transfers, String accountNumber) that receives the array of transfers and an account number. The method must then determine whether the owner of the specified account is selfish or generous. A client is deemed selfish if they have received more money than they have transfer to other accounts. They are deemed generous if they have transferred more money to other accounts than they received. For a given account number, this method should display one of the following messages: The owner of account 5105620786 is generous 6 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 or… The owner of account 5105620786 is selfish or… The owner of account 5105620786 is neither selfish or generous QUESTION SIX: NOUGHTS & CROSSES [30 marks] Noughts & Crosses, also known as tic-tac-toe, is a game we all enjoyed while growing up. The objective of the game is to align your three pieces either vertically, horizontally, or diagonally within a 3-by-3 grid before your opponent does. You and your opponent each take turns to play the game. A sample run of the game is shown below: -------------- | | | | -------------- | | | | -------------- | | | | -------------- Enter row: 0 Enter column: 1 Your move. -------------- | | X | | -------------- | | | | -------------- | | | | -------------- Computer's move. -------------- | O | X | | -------------- | | | | -------------- | | | | -------------- Enter row: 1 Enter column: 1 7 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 Your move. -------------- | O | X | | -------------- | | X | | -------------- | | | | -------------- Computer's move. -------------- | O | X | | -------------- | | X | O | -------------- | | | | -------------- Enter row: 3 Enter column: 0 Your move. (3, 0) is outside grid. Enter row: 2 Enter column: 0 Your move. -------------- | O | X | | -------------- | | X | O | -------------- | X | | | -------------- Computer's move. -------------- | O | X | | -------------- | | X | O | -------------- | X | | O | -------------- Enter row: 0 Enter column: 2 8 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 Your move. -------------- | O | X | X | -------------- | | X | O | -------------- | X | | O | -------------- Congratulations you have won the game! This game has been implemented in Java using three classes. A Board class contains methods used to keep track of the state of the game, to place a piece on the board, and to check whether the player (X) or the computer (0) has won the game. A class called Computer represents the computer a user plays against. It contains various game playing strategies that can be used by the computer to choose the next location for its piece. Finally, there is also a Game class which represents an instance of a game being played. It contains the game loop, which will continuously prompt the user to enter a piece is neither player has won, and if there are still more locations on the board that are available. For this question, you are only required to complete the Board class. We’ll assume that the other classes have been fully implemented. Below are the contents of the Board class: class Board { public static int PLAYER = 1; public static int COMPUTER = 0; private int placementCount = 0; private int[][] grid = new int; public Board() { for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[i].length; j++) { grid[i][j] = -1; } } } } At the moment the class only contains four attributes and a constructor. The constructor initialises each element in the grid matrix to a value of -1, to indicate that no piece has been placed in it yet. 9 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 Answer the following to complete the class. 6.1. Implement the toString() method for the Board class. This method (10) should print out a neat image of the current state of the board, showing where both the player (X) and computer pieces (0) are located. 6.2. Implement a method called getOpenSpaces() which returns a 2D (10) array that represents all of the spaces currently not occupied by a piece. For example, if the open spaces are locations (0,2), (1,0) and (2, 1), then the method needs to return the following array: {{0, 2}, {1, 0}, {2, 1} } If there are no more empty spaces, the method must return an empty 2D array. 6.3. Implement a method called hasWon(int turn) that determines (20) whether the player or computer has won. The parameter turn is used to indicate whether we are checking if the player (1) or computer (0) has won. This method will return true if the player or computer has won, and false if they haven’t. It checks whether the player or computer have been able to align three pieces vertically, horizontally, or diagonally. 10 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 API DOCUMENTATION String Class char charAt(int index) //Returns the char value at the specified index. int compareTo(String anotherString) //Compares two strings lexicographically. int compareToIgnoreCase(String str) //Compares two strings lexicographically, ignoring case differences. String concat(String str) //Concatenates the specified string to the end of this string. boolean endsWith(String suffix) //Tests if this string ends with the specified suffix. boolean equals(Object anObject) //Compares this string to the specified object. boolean equalsIgnoreCase(String anotherString) //Compares this String to another String, ignoring case considerations. int indexOf(int ch) //Returns the index within this string of the first occurrence //of the specified character. int indexOf(int ch, int fromIndex) //Returns the index within this string of the first occurrence of //the specified character, starting the search at the specified index. int indexOf(String str) //Returns the index within this string of the first occurrence //of the specified substring. int indexOf(String str, int fromIndex) //Returns the index within this string of the first occurrence //of the specified substring, starting at the specified index. boolean isEmpty() //Returns true if, and only if, length() is 0. int length() //Returns the length of this string. 11 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 String replace(char oldChar, char newChar) //Returns a new string resulting from replacing all occurrences of //oldChar in this string with newChar. boolean startsWith(String prefix) //Tests if this string starts with the specified prefix. String substring(int beginIndex) //Returns a new string that is a substring of this string. String substring(int beginIndex, int endIndex) //Returns a new string that is a substring of this string //from beginIndex upto endIndex−1. String toLowerCase() //Converts all of the characters in this String to lower case. String toUpperCase() //Converts all of the characters in this String to upper case. String trim() //Returns a copy of the string, with leading and //trailing whitespace omitted. String[] split(String separator) //Splits the string into tokens using the String separator as //delimiter. Returns an array containing the tokens. StringBuilder Class StringBuilder() // Constructs a string buffer with no characters in it and an // initialcapacity of 16 characters. StringBuilder(int capacity) //Constructs a string buffer with no characters in it and the //specified initial capacity. StringBuilder(String str) //Constructs a string buffer initialized to the contents of //the specified string. StringBuilder append(char c) //Appends the string representation of the char argument to //this sequence. StringBuilder append(String str) //Appends the specified string to this character sequence. //Various other append methods exist for appending integers, //doubles and strings. 12 UNIVERSITY OF KWAZULU-NATAL, NOVEMBER 2023 MOCK EXAM: COMP102WP2 char charAt(int index) //Returns the char value in this sequence at the specified //index. StringBuilder delete(int start, int end) //Removes the characters in a substring of this sequence. StringBuilder deleteCharAt(int index) //Removes the char at the specified position in this sequence. int indexOf(String str) //Returns the index within this string of the first occurrence //of the specified substring. int indexOf(String str, int fromIndex) //Returns the index within this string of the first occurrence //of the specified substring, starting at the specified index. StringBuilder insert(int offset, char c) //Inserts the string representation of the char argument into //this sequence. int lastIndexOf(String str) //Returns the index within this string of the rightmost //occurrence of the specified substring. int lastIndexOf(String str, int fromIndex) //Returns the index within this string of the last occurrence //of the specified substring. int length() //Returns the length (character count). StringBuilder replace(int start, int end, String str) //Replaces the characters in a substring of this sequence with //characters in the specified String. StringBuilder reverse() //Causes this character sequence to be replaced by the //reverse of the sequence. String substring(int start) //Returns a new String that contains a subsequence of //characters currently contained in this character sequence. String substring(int start, int end) //Returns a new String that contains a subsequence of //characters currently contained in this sequence. String toString() //Returns a string representing the data in this sequence. 13