CS1101: Programming Methodology

Slides:



Advertisements
Similar presentations
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
CS102--Object Oriented Programming
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Multidimensional arrays Many problems require information be organized as a two- dimensional or multidimensional list Examples –Matrices –Graphical animation.
15-Jun-15 Lists in Java Part of the Collections Framework.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
Files and Streams CS 21a Chapter 11 of Horstmann.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Building Java Programs
12-Jul-15 Lists in Java Part of the Collections Framework.
CS1101: Programming Methodology Aaron Tan.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Arrays And ArrayLists - S. Kelly-Bootle
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
Preventing and Correcting Errors
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Java SE 8 for Programmers, Third Edition
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Chapter 18 Java Collections Framework
CS1101: Programming Methodology Aaron Tan.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CS1101: Programming Methodology
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Chapter 5: Control Structures II
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
WEEK 6 Class Activities Lecturer’s slides.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CS1101: Programming Methodology
CS1101: Programming Methodology
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter 9 Introduction to Arrays Fundamentals of Java.
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
CS1101: Programming Methodology Aaron Tan.
(like an array on steroids)
Chapter 5: Control Structures II
TCSS 143, Autumn 2004 Lecture Notes
Fundamental Error Handling
TCSS 143, Autumn 2004 Lecture Notes
Presentation transcript:

CS1101: Programming Methodology

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 (AY Semester 1)Week9 - 2

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 (AY Semester 1)Week9 - 3

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 (AY 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

Array with different row lengths (2/2)  Code to process such array © CS1101 (AY 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(); }

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 (AY 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.

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 (AY Semester 1)Week9 - 7

Matrix Addition (2/2) © CS1101 (AY 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; }

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 (AY Semester 1)Week9 - 9

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 (AY Semester 1)Week9 - 10

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:  © CS1101 (AY Semester 1)Week9 - 11

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 (AY Semester 1)Week9 - 12

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  © CS1101 (AY Semester 1)Week9 - 13

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 (AY Semester 1)Week9 - 14

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 (AY Semester 1)Week9 - 15

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 (AY Semester 1)Week9 - 16

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 (AY Semester 1)Week9 - 17

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 (AY Semester 1)Week9 - 18

Iterator (2/2) © CS1101 (AY Semester 1)Week 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

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 (AY Semester 1)Week 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 }

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 (AY Semester 1)Week9 - 21

Collections Algorithms (2/3) © CS1101 (AY Semester 1)Week 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); }

Collections Algorithms (3/3) Output: © CS1101 (AY Semester 1)Week 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]

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 (AY Semester 1)Week9 - 24

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 (AY Semester 1)Week9 - 25

Writing Robust Programs (2/3) Refer to WrongInput.java  User enters a string: © CS1101 (AY Semester 1)Week  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: 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.

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 (AY Semester 1)Week9 - 27

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 (AY Semester 1)Week9 - 28

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

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 (AY Semester 1)Week9 - 30

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