Download Week9 - NUS School of Computing

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS1101: Programming Methodology
http://www.comp.nus.edu.sg/~cs1101/
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
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
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:
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);
3
2
4
3
array2D
1
8
6
3
9
2
7
© CS1101 (AY2009-2010 Semester 1)
4
Week9 - 4
Array with different row lengths (2/2)
 Code to process such array
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
© CS1101 (AY2009-2010 Semester 1)
Week9 - 5
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.
a1  1 a 1 2  a 1 n
a2  1 a 2 2  a 2 n


am  1 a m 2  a m n

Note that in implementing the matrix as an array in
Java, the row number and column number start at 0
instead of 1.
© CS1101 (AY2009-2010 Semester 1)
Week9 - 6
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
ci,j = ai,j + bi,j
 Example on 33 matrices:
1 2 0
 1 0 0 




0 1 1   2 1 0 
1 0 1
 0 2  1




© CS1101 (AY2009-2010 Semester 1)
 0 2 0


  2 2 1
 1 2 0


Week9 - 7
Matrix Addition (2/2)
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;
}
© CS1101 (AY2009-2010 Semester 1)
Week9 - 8
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
Matrix Multiplication (2/2)
 To compute C = A  B, where A, B, C are matrices
ci,j = (ai,1  b1,j ) + (ai,2  b2,j ) + . . . + (ai,n  bn,j )
ci,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:
1 2 0
 1 0 0 




0 1 1   2 1 0 
1 0 1
 0 2  1




© CS1101 (AY2009-2010 Semester 1)
3 2 0


  2 3  1
  1 2  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:
 http://www.comp.nus.edu.sg/~cs1101/3_ca/labs.html
© CS1101 (AY2009-2010 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 (AY2009-2010 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

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
© CS1101 (AY2009-2010 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 (AY2009-2010 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 (AY2009-2010 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 (AY2009-2010 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 (AY2009-2010 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
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
Iterator (2/2)
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
Individual import statements shown to
show what actually are imported. The usual
import java.util.* will still work.
class DemoIterator {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
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));
}
Same output
Iterator it = myList.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
© CS1101 (AY2009-2010 Semester 1)
Week9 - 19
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:
import java.util.*;
class Josephus {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String> nameList = readNameList(scanner);
System.out.print("Enter k: ");
int k = scanner.nextInt();
simulateJosephus(nameList, k);
}
// fill in readNameList() method
// fill in simulateJosephus() method
}
© CS1101 (AY2009-2010 Semester 1)
Week9 - 20
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
Collections Algorithms (2/3)
import java.util.*;
public class DemoCollections {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
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);
}
}
© CS1101 (AY2009-2010 Semester 1)
Week9 - 22
Collections Algorithms (3/3)

Output:
Original:
Reversed:
Shuffled:
Sorted :
[0,
[9,
[3,
[0,
© CS1101 (AY2009-2010 Semester 1)
1,
8,
0,
1,
2,
7,
1,
2,
3,
6,
9,
3,
4,
5,
5,
4,
5,
4,
2,
5,
6,
3,
8,
6,
7,
2,
6,
7,
8,
1,
7,
8,
9]
0]
4]
9]
Week9 - 23
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
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
Writing Robust Programs (2/3)

Refer to WrongInput.java

User enters a string:
An exception is thrown.
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)

User enters a real number:
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)
© CS1101 (AY2009-2010 Semester 1)
Week9 - 26
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
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
Summary for Today



2-dimensional arrays
ArrayList
Exceptions
© CS1101 (AY2009-2010 Semester 1)
Week9 - 29
Announcements/Things-to-do

Complete the following



Take-home lab #5


Deadline: 26 October 2009, Monday, 23:59hr
To prepare for next lecture


Matrices.java (to be discussed in next week’s lecture)
Josephus.java (to be discussed in this Friday’s discussion)
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
End of File
© CS1101 (AY2009-2010 Semester 1)
Week9 - 31