COMP102 TEST 2 NOTES.pdf
Document Details
Uploaded by TolerableOrchid6896
2024
Tags
Full Transcript
Lecture 6: Introduction to Arrays COMP102: Computer Programming August 2024 Agenda - Declare an array - Declare and initialise array - Assign values to array - Reference values in array - Display all values in array Arrays Store Collection of Data - Variables store a single value, e.g. mark = 76;...
Lecture 6: Introduction to Arrays COMP102: Computer Programming August 2024 Agenda - Declare an array - Declare and initialise array - Assign values to array - Reference values in array - Display all values in array Arrays Store Collection of Data - Variables store a single value, e.g. mark = 76; - We often need to store a collection of values - Equivalent of Python list, e.g. marks = [78, 90, 10, 6, 12, 6] - Java: array Declaration of an Array // Option 1. Full declaration double[] marks = new double; // Option 2. 2-step declaration double[] marks; marks = new double; Declaration and Initialisation double[] marks = {7.45, 9.5, 45.12, 60.0}; // Template dataType[] variableName = {v1, v2, …, vn}; Assignment of Value marks[i] = 48.6; // Template variableName[index] = value; Access of Value System.out.println(marks); // Template variableName[index] Displaying All Values in Array for(int i = 0; i < marks.length; i++) { System.out.print(marks[i] + “ “); } Ends. Lecture 7: Arrays Exercises COMP102: Computer Programming August 2024 Question 1: Largest Number Write a program that creates a double array that holds 5 numbers. Generate 5 random double numbers between 0 and 100 and assign them to the 5 slots in your array. Now find the largest number and display it on the console. Question 2: Even Odd Count Write a program that creates an integer array that can hold 15 values. Then populate this array with 15 integers in the range 0-9 inclusive. Now count the number of even and odd numbers and display this count on the console. Question 3: Counting Pairs Write a program that generates an integer array that holds 15 values. Populate this array with random integers in the range 0-9 inclusive. Now count the number of integers that appear twice in the array. Display this count on the console. Ends. Lecture 8: Strings COMP102: Computer Programming August 2024 Agenda - Declare and initialise a String - Strings as objects with methods - Looping through String - Comparing two Strings - The compareTo() method - Modifying a String - Searching a String - Other useful Methods Creating Strings Declaration and Initialisation String name; name = “Hello world!”; Declaration and Initialisation String name = “Hello world!”; String as Object String word = “Java” int length = word.length(); int indexV = word.indexOf(‘v’); word = word.toLower(); String objects in Java are immutable. Once a String object is created, it cannot be changed. If you perform any operation that alters the string (like converting it to lowercase), a new String object is created, leaving the original one unchanged. Example 1. String word = "Java"; String lowerCaseWord = word.toLowerCase(); 2. String str = "java"; String upper = str.toUpperCase(); Looping through String int: myString.length() e.g String str = "Java"; int len = str.length(); char: myString.charAt(index) e.g Comparing Strings - boolean: equals(Object str) - Difference between: equals() and == - boolean: equalsIgnoreCase(String str) - boolean: regionMatches(int start, String str2, int str2Start, int numChars) - boolean: startsWith(String str2) - boolean: endsWith(String str2, int start) e.g String str1 = "Java"; String str2 = "Java"; Region Matches boolean result = str1.equals(str2); String str1 = "Hello, world!"; String str1 = "Java"; String str2 = "Welcome to the world!"; String str2 = "java"; boolean equal = str1.equalsIgnoreCase(str2); // Compare the region "world" from both strings boolean result = str1.regionMatches(7, str2, 11, 5); String str = "Java Programming"; boolean starts = str.startsWith("Java"); // true System.out.println(result); // Output: true String str = "Java Programming"; // Let's try another region comparison that does not match boolean ends = str.endsWith("ing"); // true boolean result2 = str1.regionMatches(7, str2, 0, 5); System.out.println(result2); // Output: false compareTo() String str1 = "Java"; - int: invokingString.compareTo(str) String str2 = "JavaScript"; int result = str1.compareTo(str2); - Dictionary order: - All - aid - all - come - country - Returns value less than 0 if: invoking string is less than str - Returns value greater than 0 if: invoking string is greater than str - Returns zero if: the two strings are equal Modifying a String - String: substring() - substring(int startIndex) - substring(int startIndex, int endIndex) - String: replace() - replace(char original, char replacement) - replace(CharSequence original, CharSequence replacement) - String: trim() – removes any leading or trailing spaces String str = "Java Programming"; String sub = str.substring(5); // sub = "Programming" String str = "Java Programming"; String sub = str.substring(0, 4); // sub = "Java" String str = "Java"; String replaced = str.replace('a', 'o'); // replaced = "Jovo" String str = " Java "; String trimmed = str.trim(); // trimmed = "Java" Searching a String - All methods return -1 if character of string isn’t found - Searching for character: - int: indexOf(char ch) - int: lastIndexOf(char ch) - int: indexOf(char ch, int start) - int: lastIndexOf(char ch, int start) - Searching for String: - int: indexOf(String str) - int: lastIndexOf(String str) - int: indexOf(String str, int start) - int: lastIndexOf(String str, int start) Example String str = "Hello, world!"; // Searching for a character that exists int index1 = str.indexOf('o'); // index1 = 4 // Searching for a character that does not exist int index2 = str.indexOf('x'); // index2 = -1 String text = "Hello, welcome to the world of Java"; // Start searching from index 10 int index = text.indexOf("Java", 10); System.out.println(index); // Output: 31 // If you start searching from an index after "Java" appears int indexNotFound = text.indexOf("Java", 35); System.out.println(indexNotFound); // Output: -1 Other useful Methods - String: valueOf(dataType value) – overloaded for all primitive data types - String: toLowerCase() - String: toUpperCase() - String: join(CharSequence, delim, CharSequence …strs) String joined = String.join(" , ", "Java", "Python", "C++"); Ends. Lecture 9: Methods COMP102: Computer Programming August 2024 Agenda - Why do we use methods? - Methods in Java - Exercise 1 Consider the Following Problem Prompt a user to enter two integers. Then determine whether they have the same parity. The parity of an integer is its attribute of being even or odd. In Pseudocode get first integer get second integer determine if first number is even/odd (display message) determine if second number is even/odd (display message) determine if they have the same parity (display message) Solution in Python 1. num_one = int(input('Enter first integer: ')) 2. num_two = int(input('Enter second number: ‘)) 3 4. if(num_one % 2 == 0): 5. print(num_one, 'is even.’) 6. num_one_even = True 7. else: 8. print(num_one, 'is odd.’) 9. num_one_even = False 10. 11. if(num_two % 2 == 0): 12. print(num_two, 'is even.’) 13. num_two_even = True 14. else: 15. print(num_two, 'is odd.’) 16. num_two_even = False 17. 18. if(num_one_even == num_two_even): 19. print('Numbers have same parity.’) 20. else: 21. print('Numbers do not have same parity.') In Python Using Functions 1. num_one = int(input('Enter first integer: ')) 2. num_two = int(input('Enter second number: ‘)) 4. 5. if(is_even(num_one) == is_even(num_two)): 6. print('Number have the same parity.’) 7. else: 8. print('Number do not have same parity.’) 9. 10. def is_even(num): 11. if(num % 2 == 0): 12. print(num, 'is even.’) 13. return True 14. else: 15. print(num, 'is odd.’) 16. return False Benefits of Functions - Less code! We always want to write the least amount of code to solve a problem - Minimise the repetition of code – leverage the same function - Centralised point of change - Code looks much neater Template of Java Method public static returnType name(dataType parameter) { // body of method } Components of Method - The public and static keywords - The return type, use void keyword when method returns nothing + If you have a return type, you need to return some value using return keyword + The returned type has to match the declared type - The name of the method - The method parameter(s) isEven() Method Declaration public static Boolean isEven(int num) { // body of method } isEven() Method in Full public static Boolean isEven(int num) { if(num % 2 == 0){ System.out.println(num + " is even."); return true; } else { System.out.println(num + " is odd."); return false; } } Calling methods It is only legal to call a method if is has been defined. The order of parameters in the method definition must match the order of the arguments for those parameters when the method is called. Methods can call other methods within them if the called method is in a valid scope/context to be called in the other method calling it. Question 1: Palindrome A palindrome is a word that has the same spelling when the letters are reverse. For example, the following are all palindromes: “radar”, “civic”, “defied”, “level”, “rotator” Write a method that receives a word and determines whether it is a palindrome or not. It should return the Boolean value “true” if it is, and “false” if it isn’t. To test your method by prompting a user for a word and telling them whether it is a palindrome or not. Ends. Lecture 10: Introduction to 2D Arrays COMP102: Computer Programming August 2024 Test 1 - 30 August 2024 - Venue : SU - Time : 14: 10 - 60 minutes long - Coding Agenda - Declare a 2D array - Declare and initialise a 2Darray - Assign values to 2D array - Reference values in 2D array - Display all values in 2D array 1D Array 2D Array In practice, we may need more dimensions into our arrays to store data in a more organized way, e.g., to store the dates of a month, we may want to separate it into weeks (an array for each week) and all those weeks be contained in one moth (an outer array). The syntax for declaring two dimensional arrays requires that the number of rows and columns must be specified. E.g., in the dates of a month, the number of rows can be the number of weeks in a month. The number of columns can be the number of days in the month. 2D Array Coordinates Declare a 2D Array The generic syntax for declaring two dimensional arrays is as follows: dataType[][] arrayName = new dataType[rowSize][columnSize]; For example, for the a month with 4 full weeks, the two dimensional array for storing the dates would be as follows: int[][] monthDates= new int ; // Option 1. Full declaration double[][] marks = new double; // Option 2. 2-step declaration double[][] marks; marks = new double; Declare and Initialise Array double[][] marks = {{7.8, 90, 4.5, 60, 9}, {55, 34, 87, 8.7, 20}, {40, 9.2, 90, 80, 6.7}, {80, 100.7, 93.7, 56, 7.2}, {10.15, 100, 45.8, 30, 9.1} }; Declaration and Initialisation Template dataType[][] variableName = {{val_1, val_2,…, val_n}, {val_1, val_2,…, val_n},... {val_1, val_2,…, val_n} }; Assign Value to Specific Slot marks[i][j] = 48.6; // Template variableName[row][column] = value; Access Value in Specific Slot System.out.println(marks); // Template variableName[row][column] Traversing 2 Dimensional Arrays / Display All Values in Array Traversing two dimensional arrays requires one loop to iterate the rows (as elements of the outer array) and another loop to iterate the columns (the elements of the inner arrays). This operation can be done as follows: for(int i = 0; i < marks.length; i++) { for(int j = 0; j < marks.length; j++) { System.out.print(marks[i][j] + “ “); } System.out.println(); } for (int row = 0; row< 4; row++) { for (int col = 0; col< 7; col++) { System.out.print( monthDates[ row] [ col] + " "); } System.out.println(); //go to next line } The end. Lecture 14: Object- Oriented Programming COMP102: Computer Programming September 2024 Procedural Programming: Java Another Example: Dlamini Problem 1. Generate a random square matrix with numbers in range 0-9 2. Display the square matrix 3. Declare a tracker array to record each occurrence of a digit in each row 4. Process tracker array to remove all duplicate recording of a digit in a particular row 5. For each digit check if the string in the tracker array is equal in length to the number of rows in square matrix Key Limitation: Complexity - Complexity of real problems is much greater: - Traction control software on car - Autopilot on aircraft - Facebook - University Administration System - Procedural programming not good for dealing with complexity - Software is object specific to problem Object-Oriented Programming Programming framework where we identify the entities in our problem space that can be used to design a solution. This solution will comprise of a set of classes that represent the entities. These classes contain attributes that represent properties of the entities. They also contain methods which capture the behaviours that the entities have. The problem is thus solved by the interaction of objects created from these classes. Previously: Student Registration System Now: OOP Solution Design Procedural Programming URL: https://www.grit.com/far m-and- garden/structures-and- outbuildings/build- simple-bridge- zm0z22mjzols/ Accessed: 11 September 2023 Object-oriented Programming URL: https://en.wikipedia. org/wiki/Spaghetti_ju nction Accessed: 11 September 2023 Benefits of Added Complexity - Easier to understand complex solution designed in OOP - More reliable because we understand software better - More likely to be accurate - We can reuse parts of current solution for another problem (libraries) Examples of OOP You Know Scanner input = new Scanner(System.in); Random rand = new Random(); String name = “Siya”; String fullName = new String(“Eben Etzebeth”); Has attributes and behaviors Object Attributes also called properties characteristics that describe the object simply called object's data Example 1.2: car's attributes are: registration number, make, model, color, size. Example 1.3: Student's attributes are: student number, name, surname, address, date of birth, gender, nationality. Exercise 1.1: Give some attributes of a rectangle and a bank account objects. Exercise 1.2: Give some attributes (at least three) of GUI objects: a room, a shirt, and a cellphone Object Behavior Also called methods Describe what an object can do Operations that can be performed on the object's data (attributes or properties) Example 1.4: car's methods are: start, drive, stop Example 1.5: student's methods are: register, attend lectures, write exam, get mark, etc. Exercise 1.3: Give some methods or behaviors (at least two) of a rectangle and a bank account [Step 3.] Student Class Attributes: - Name - Surname - Student number - Date of birth Methods: - Get full name - Get age [Step 3.] Registration Class Attributes: - Student number - Time and date - Course Methods: - Deregister - Get status - Append concession [Step 4.] Objects of Student [Step 4.] OOP Solution Design Procedural vs. OOP - Procedural: - We declare variables (state of program) - Then we manipulate the values - Problem is solved by execution of explicit statements from top to bottom - Object-Oriented Programming: - We design classes - Objects contain data and means of manipulating that data - Problems are solved by interaction of objects Our Work in Coming Weeks… 1. Read problem statement 2. Identify the entities relevant to our solution design 3. Map the entities to classes, identifying the attributes and methods 4. Write a program that uses objects created from our classes to solve a problem Ends. Lecture 15: OOP Exercise COMP102: Computer Programming September 2024 Creating a Student Class Agenda 1. Create the Student class 2. Create get and set methods to control access to state 3. Create a constructor to safely create Student objects Creating a Vehicle Class Objective: Implement the Vehicle class and the TestVehicle class based on the UML diagram provided. Note: getLitres(): A method that calculates and returns the fuel consumed in liters based on the distance and FuelEfficiency using the following formular (efficiency/100)* distance. Creating a Time Class Ends. Lecture 15: Exception Handling COMP102: Computer Programming September 2024 Einstein’s Definition of Insanity “The definition of insanity is --- doing the same thing over and over and expecting a different result.” Importance of Practice in Learning Skill How to use tools How to do stuff (cut pieces, join pieces) Knowledge – strong sturdy structures Abstract thinking for creating and implementing design https://images.app.goo.gl/6V1y2HPJBZXkj9BA9 (Accessed 16 September 2024) Don’t Underestimate Task at Hand Mastery required for transfer to new problem Mastery fosters confidence (seen this problem/solved a similar problem) Mastery allows you to see patterns in problem and recall building blocks of solution How to Think About Test 1 Result 1. Result is a judgement of my intelligence and ability (wrong!) 2. Reflection of my current understanding and mastery (right!) Current understanding and mastery, given: time + effort I’ve put into the course Still Time for Turnaround Assessment Weight Date Practical’s 5% Friday afternoon Test 1 15% 30th August 2024 Test 2 10% 4 October 2024 Practical Test 20% 11 October 2024 Exam 50% 14th November 2024 [Plan to Pass] Course Calendar Week Work 30 September Test 2 [Friday] File processing 7 October Testing 14 October Practical Test [Friday] 21 October Make-up Tests Exceptions Consider Following Program Output: Expected Output: Bad What’s an Exception - “An exception is an abnormal condition that arises in a code sequence at run time.” – Java: The Complete Reference (11 ed.) – Herbert Schildt (Danny Coward, technical editor) - Three types of errors: - Syntax or compile-time errors - Logical errors - Runtime errors - Sources of exceptions: - Java Virtual Machine - Your source code Causes of Exceptions Java’s Error Handling Mechanism - Has four components: - Exception classes - throws clause - try-catch statement - throw statement try-catch Statement try { // Risky code which could cause an exception to be thrown } catch (Exception e) { // What must happen if an exception is thrown } finally { // Executed whether or not exception is thrown } New Code Output: Errors Handled Gracefully Ends.