Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1101: Programming Methodology

Similar presentations


Presentation on theme: "CS1101: Programming Methodology"— Presentation transcript:

1 CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101/ http://www.comp.nus.edu.sg/~cs1101/

2 Week 9: 2D Arrays, ArrayLists & Exceptions  Previous lecture:  Chapter 9: Characters and Strings  Chapter 10: Arrays and Collections  This week:  Chapter 10: Arrays and Collections (cont’d)  Chapter 8: Exceptions  Next week:  Chapter 11: Sorting and Searching © CS1101 (AY2009-2010 Semester 1)Week9 - 2

3 Chapter 10 Arrays and Collections We covered up to one-dimensional arrays last week Let’ go over Thomas Wu’s slides now for the rest of the chapter… For List interface, we will focus on ArrayList class. We will skip Map interface as it is not in the syllabus. © CS1101 (AY2009-2010 Semester 1)Week9 - 3

4 Array with different row lengths (1/2)  Since a two-dimensional array is actually an array of arrays, we can create a 2D array with rows of different lengths.  For example: © CS1101 (AY2009-2010 Semester 1)Week9 - 4 int[][] array2D = { {3,1,8}, {6,3}, {9,2,7,4} }; System.out.println(arr[0].length); System.out.println(arr[1].length); System.out.println(arr[2].length); array2D 3 1 8 6 3 9 2 7 4 324324

5 Array with different row lengths (2/2)  Code to process such array © CS1101 (AY2009-2010 Semester 1)Week9 - 5 int[][] array2D = { {3,1,8}, {6,3}, {9,2,7,4} }; for (int i=0; i<array.length; i++) { for (int j=0; j<array[i].length; j++) System.out.print(array[i][j] + " "); System.out.println(); } 3 1 8 6 3 9 2 7 4

6 Matrices A two-dimensional array where all rows have the same length is sometimes known as a matrix because it resembles that mathematical concept. A matrix A with m rows and n columns is represented mathematically in the following manner. © CS1101 (AY2009-2010 Semester 1)Week9 - 6 Note that in implementing the matrix as an array in Java, the row number and column number start at 0 instead of 1.

7 Matrix Addition (1/2)  To add two matrices, both must have the same number of rows, and the same number of columns.  To compute C = A + B, where A, B, C are matrices c i,j = a i,j + b i,j  Example on 3  3 matrices: © CS1101 (AY2009-2010 Semester 1)Week9 - 7

8 Matrix Addition (2/2) © CS1101 (AY2009-2010 Semester 1)Week9 - 8 public static int[][] matrixSum(int[][] arrA, int[][] arrB) { // determine number of rows in solution int m = arrA.length; // determine number of columns in solution int n = arrB[0].length; // create the array to hold the sum int[][] arrC = new int[m][n]; // compute the matrix sum row by row for (int i = 0; i < m; i++) { // produce the current row for (int j = 0; j < n; j++) { arrC[i][j] = arrA[i][j] + arrB[i][j]; } return arrC; }

9 Matrix Multiplication (1/2)  To multiply two matrices A and B, the number of columns in A must be the same as the number of rows in B.  The resulting matrix has same number of rows as A and number of columns as B.  For example, multiplying a 4  5 matrix with a 5  3 matrix gives a 4  3 matrix. © CS1101 (AY2009-2010 Semester 1)Week9 - 9

10 Matrix Multiplication (2/2)  To compute C = A  B, where A, B, C are matrices c i,j = (a i,1  b 1,j ) + (a i,2  b 2,j ) +... + (a i,n  b n,j ) c i,j is sum of terms produced by multiplying the elements of A’s row i with B’s column j.  Example on 3  3 matrices: © CS1101 (AY2009-2010 Semester 1)Week9 - 10

11 Exercise: Matrices.java  Download Matrices.java and complete the matrixProduct() method.  Try AY2007/8 Semester 1 lab #7 exercises:  Sudoku  Rabbit Jumps  Polygon  Go to course website, “Labs” page to retrieve last year’s lab write-ups:  http://www.comp.nus.edu.sg/~cs1101/3_ca/labs.html http://www.comp.nus.edu.sg/~cs1101/3_ca/labs.html © CS1101 (AY2009-2010 Semester 1)Week9 - 11

12 System.err.println() and System.exit()  In Matrices.java, you will find two new features.  In a computing system, there are 3 data streams:  Input stream  Output stream  Error stream  System.err.println() prints output to the error stream  The error stream and output stream use the same device (monitor)  System.exit(n) terminates the program  The integer n is an exit code specified by you, usually a positive integer.  After exiting the program, you may check the exit code (how to do this depends on the operating system you are using) to determine where the program exit. © CS1101 (AY2009-2010 Semester 1)Week9 - 12

13 ArrayList (1/3) Arrays have their limitations  Inserting an element into the array at a specific index requires shifting other elements  Same for deleting an element at the specific index in an array We shall study ArrayList  http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html © CS1101 (AY2009-2010 Semester 1)Week9 - 13

14 ArrayList (2/3) Some methods in ArrayList  add(E e): Appends element to end of list  add(int index, E e): Inserts element at specified position  isEmpty(): Returns true if list contains no elements  size(): Returns number of elements  remove(int index): Removes the element at the specified position  set(int index, E e): Replace the element at the specified position with the specified element © CS1101 (AY2009-2010 Semester 1)Week9 - 14

15 ArrayList (3/3) We will use the Person class in Chapter 10. We will create an ArrayList of Person objects. See program ArrayListOfPersons.java © CS1101 (AY2009-2010 Semester 1)Week9 - 15

16 Lists and Primitive Data Types (1/2) With an array, we can store primitive data values or objects. But with a list (eg: ArrayList), we can store only objects. To store primitive data values in a list, we use wrapper classes  For example, wrapper class for int is Integer, for double is Double, etc. © CS1101 (AY2009-2010 Semester 1)Week9 - 16

17 Lists and Primitive Data Types (2/2) See program ArrayListOfIntegers.java  It looks similar to ArrayListOfPersons.java Java’s automatic boxing and unboxing allows for more simplified codes. See program ArrayListOfIntegersWithAutoBoxing.java © CS1101 (AY2009-2010 Semester 1)Week9 - 17

18 Iterator (1/2) A very common process is examining every element in a collection. The ArrayList class provides a special way to iterate over its element.  The iterator() method of ArrayList returns an Iterator object.  Iterator is an interface Iterator  Need to import java.util.Iterator Methods provided in Iterator:  boolean hasNext() Returns whether this Collection has more elements to return.  Object next() Returns next element of this Collection. If there is no next element, it throws a NoSuchElementException.  void remove() Remove from this Collection the last element returned by the iterator. © CS1101 (AY2009-2010 Semester 1)Week9 - 18

19 Iterator (2/2) © CS1101 (AY2009-2010 Semester 1)Week9 - 19 import java.util.List; import java.util.ArrayList; import java.util.Iterator; class DemoIterator { public static void main(String[] args) { List myList = new ArrayList (); myList.add(new Integer(12)); myList.add(new Integer(7)); myList.add(new Integer(-98)); for (int i = 0; i < myList.size(); i++) { System.out.println(myList.get(i)); } Iterator it = myList.iterator(); while (it.hasNext()) { System.out.println(it.next()); } Individual import statements shown to show what actually are imported. The usual import java.util.* will still work. Same output

20 Josephus Problem Download week9_discussion_qns.pdf Try out the Josephus Problem (question 20) now (and continue if you are unable to complete in class) Partial code given below: © CS1101 (AY2009-2010 Semester 1)Week9 - 20 import java.util.*; class Josephus { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List nameList = readNameList(scanner); System.out.print("Enter k: "); int k = scanner.nextInt(); simulateJosephus(nameList, k); } // fill in readNameList() method // fill in simulateJosephus() method }

21 Collections Algorithms (1/3) A collection of algorithms for performing standard list operations. (Not in syllabus, but nice to know.) Algorithms are implemented as class methods of the class java.util.Collections Several methods make use of the interfaces java.lang.Comparable or java.util.Comparator public int compareTo(Object v) Returns a negative value if this object is less than v; returns zero if the two objects are equal; and returns a positive value otherwise. public int compareTo(Object v1, Object v2) Returns a negative value v1 is less than v2; returns zero if the two values are equal; and returns a positive value otherwise. public boolean equals(Object v) Returns true or false, whether v is equal to this object. © CS1101 (AY2009-2010 Semester 1)Week9 - 21

22 Collections Algorithms (2/3) © CS1101 (AY2009-2010 Semester 1)Week9 - 22 import java.util.*; public class DemoCollections { public static void main(String[] args) { List myList = new ArrayList (); for (int i = 0; i < 10; i++) myList.add(new Integer(i)); System.out.println("Original: " + myList); Collections.reverse(myList); System.out.println("Reversed: " + myList); Collections.shuffle(myList); System.out.println("Shuffled: " + myList); Collections.sort(myList); System.out.println("Sorted : " + myList); }

23 Collections Algorithms (3/3) Output: © CS1101 (AY2009-2010 Semester 1)Week9 - 23 Original: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reversed: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Shuffled: [3, 0, 1, 9, 5, 2, 8, 6, 7, 4] Sorted : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

24 Errors in Program System.err.println() and System.exit() were introduced in Matrices.java We will now study Exceptions How to check what error (exceptions) occurs and how to handle (catch) the error © CS1101 (AY2009-2010 Semester 1)Week9 - 24

25 Writing Robust Programs (1/3) Suppose you have this statement int value = scanner.nextInt(); So far, we assume that the user always follows instructions and never enters the wrong type of data. But what if the user enters the following data in response to the above statement?  A string (eg: “apple”)?  A real number (eg: 12.3)? © CS1101 (AY2009-2010 Semester 1)Week9 - 25

26 Writing Robust Programs (2/3) Refer to WrongInput.java  User enters a string: © CS1101 (AY2009-2010 Semester 1)Week9 - 26  User enters a real number: Enter an integer: apple Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000) at WrongInput.main(WrongInput.java:14) Enter an integer: 12.34 Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000) at WrongInput.main(WrongInput.java:14) An exception is thrown.

27 Writing Robust Programs (3/3) An exception is thrown when an error occurs. If the exception is not caught, the program crashes. We would like to catch the exception so that the program does not crash. Let’s go on to Chapter 8. (We will skip Assertions.) © CS1101 (AY2009-2010 Semester 1)Week9 - 27

28 Using throws to postpone catch Download StudentList.java and StudentListDriver.java and study them. Download StudentList2.java and StudentList2Driver.java and study them. For checked exceptions, if you do not have a try-catch block, then you must add ‘throws’ at the header of the method. For unchecked exceptions, it is optional to add ‘throws’ at the header. © CS1101 (AY2009-2010 Semester 1)Week9 - 28

29 Summary for Today 2-dimensional arrays ArrayList Exceptions © CS1101 (AY2009-2010 Semester 1)Week9 - 29

30 Announcements/Things-to-do Complete the following  Matrices.java (to be discussed in next week’s lecture)  Josephus.java (to be discussed in this Friday’s discussion) Take-home lab #5 Deadline: 26 October 2009, Monday, 23:59hr To prepare for next lecture  Read Chapter 11 Sorting and Searching and the PowerPoint file before you come for lecture. To prepare for this Friday’s discussion session  Download “week9_discussion_qns.pdf” from module website, “CA – Discussion”.  Do the questions before you attend your discussion session. © CS1101 (AY2009-2010 Semester 1)Week9 - 30

31 End of File © CS1101 (AY2009-2010 Semester 1)Week9 - 31


Download ppt "CS1101: Programming Methodology"

Similar presentations


Ads by Google