CS 1101 Programming Methodology http www comp nus

  • Slides: 36
Download presentation
CS 1101: Programming Methodology http: //www. comp. nus. edu. sg/~cs 1101/

CS 1101: Programming Methodology http: //www. comp. nus. edu. sg/~cs 1101/

Week 8: Strings and Arrays § Previous lecture: § Chapter 7: Defining Your Own

Week 8: Strings and Arrays § Previous lecture: § Chapter 7: Defining Your Own Classes – Part 2 § This week: § Chapter 9: Characters and Strings § Chapter 10: Arrays and Collections § Next week: § Chapter 10: Arrays and Collections (cont’d) § Chapter 8: Exceptions © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 2

Chapter 9 Characters and Strings n Let’ go over Thomas Wu’s slides now… ©

Chapter 9 Characters and Strings n Let’ go over Thomas Wu’s slides now… © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 3

Quizzes n n n Are 'A' and "A" the same thing? Why? Can char

Quizzes n n n Are 'A' and "A" the same thing? Why? Can char be used in a switch statement? How about a String object? Show the results, or if it is illegal, how to correct it. (ASCII value of 'a' is 97. ) 1. 2. 3. 4. 5. + System. out. println('a' + "xyz"); System. out. println('a' + 123); System. out. println('a' + 'b'); if ("a" < "b"). . . if ("abc" < "xx"). . . © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 4

Do not overuse String n Some students like to use String to solve numerical

Do not overuse String n Some students like to use String to solve numerical problems, because there are so many methods available for String. q q q n n For example, given an integer, extract its individual digits. No good: convert the integer to a string, use substring to extract the individual characters, then convert each character to a digit. Better: use division (/) and modulo (%), like what we did for Matriculation check code. Manipulating strings can use up a lot of space, due to its immutability. Strings are special. There are two ways to create a String object: with or without using ‘new’ statement. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 5

Two ways of creating String objects We can do this because String objects are

Two ways of creating String objects We can do this because String objects are immutable. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 6

String: Effect of Immutability n Example 1: String s = "abc"; s = s

String: Effect of Immutability n Example 1: String s = "abc"; s = s + "def"; q n A new string "abcdef" is created for s in the second statement. (Hence, it uses more memory. What happens to the memory space that stores "abc"? ) Example 2: String s 1 = "abc"; String s 2 = "abc"; s 1 = "xyz"; q n String s 2 still refers to "abc". (Imagine the horror if this is not so!) Hence, String objects behave differently from other objects or arrays. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 7

Exercise: Counting “the” (1/2) n n Write a program Ch 9 Count. The. java

Exercise: Counting “the” (1/2) n n Write a program Ch 9 Count. The. java to count the number of times user entered the word “the”. The program ends when the user enters an empty string. The word “the” may be entered with leading or/and trailing spaces, and it may contain uppercase or lowercase letter. (This question is the same as question 1 in Week 9’s discussion. ) © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 8

Exercise: Counting “the” (2/2) n A sample run: q q User’s inputs are shown

Exercise: Counting “the” (2/2) n A sample run: q q User’s inputs are shown in blue Space is denoted by the �character Enter a string: Enter a string: Number of times n t. He quick ���� �� THE� th. E��� "the" appears: 3 Look up the String API page for appropriate String methods to use. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 9

Take-home lab assignment #4 n n It has been released more than a week

Take-home lab assignment #4 n n It has been released more than a week ago. Deadline is Monday, 12 October 2009, 23: 59 hr. Any questions? © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 10

Motivation (1/3) n Task: Find the minimum value of 3 integers int min; if

Motivation (1/3) n Task: Find the minimum value of 3 integers int min; if ( (value 1 <= value 2) && (value 1 <= value 3) ) min = value 1; else if ( (value 2 <= value 1) && (value 2 <= value 3) ) min = value 2; else if ( (value 3 <= value 1) && (value 3 <= value 2) ) min = value 3; n What if the list is big? q Code will be longer – the logical expression in each ‘if’ statement will be longer and more complex. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 11

Motivation (2/3) n Consider this algorithm int min = value 1; if (value 2

Motivation (2/3) n Consider this algorithm int min = value 1; if (value 2 < min) min = value 2; if (value 3 < min) min = value 3; n What if the list is big? q Code will still be longer, but if we make use of the regular pattern and the array structure for the data, we can ‘roll’ the if statements into a loop. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 12

Motivation (3/3) n Using the array structure int min = value[0]; if (value[1] <

Motivation (3/3) n Using the array structure int min = value[0]; if (value[1] < min) min = value[1]; if (value[2] < min) min = value[2]; n Rolling into a loop using array subscript/index: int min = value[0]; for (int k = 1; k < 3; k++) { if (value[k] < min) min = value[k]; } n The above code can be easily modified for a bigger list. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 13

Chapter 10 Arrays and Collections (1/2) n In computer science, we deal with very

Chapter 10 Arrays and Collections (1/2) n In computer science, we deal with very large amount of data q q n n Eg: 3000 integers, 265 days, 1 million real numbers. Do you want to create so many variables in your program? If the data are homogeneous (of the same type), we can organise them into a single collection (we normally call it a list). Array is an implementation of a list. It is an indexed collection of homogeneous data. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 14

Chapter 10 Arrays and Collections (2/2) n n n We will cover up to

Chapter 10 Arrays and Collections (2/2) n n n We will cover up to one-dimensional arrays today, and continue from two-dimensional arrays next week. The syntax for array is very simple, yet learning it allows us to solve many interesting problems. Let’ go over Thomas Wu’s slides now… © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 15

Array Declaration Syntax § Array declaration syntax: <element-type>[] <array-variable>; Example: double[] values; § Alternative

Array Declaration Syntax § Array declaration syntax: <element-type>[] <array-variable>; Example: double[] values; § Alternative syntax: <element-type> <array-variable>[]; Example: double values[]; § I prefer the first one, it’s more readable and meaningful. The second form is more commonly used by C/C++ programmers. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 16

Basic Terminology § An array is a form of ordered list. § A list

Basic Terminology § An array is a form of ordered list. § A list is composed of elements. § List is homogeneous – elements are of the § § § same base type. Elements in a list have a common name. The list as a whole is referenced through the common name. Elements are referenced by subscripting (indexing) the common name. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 17

Java Array Features § Subscripts/indices are denoted as expressions within § § square brackets

Java Array Features § Subscripts/indices are denoted as expressions within § § square brackets [ ] Size of array (number of elements) can be specified at run time Index type is integer and index range must be 0 … n 1 where n is the array size Automatic bounds checking Array is an object q Has features common to all other objects © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 18

Common mistake: length() vs length n Do not mix up the two q The

Common mistake: length() vs length n Do not mix up the two q The length of a String object str is obtained by calling the String method length() § q Example: str. length() The length (size) of an array arr is stored in its data member length § Example: arr. length © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 19

Classic Array Problems § Compute statistics (sum, mean, standard § § deviation, etc. )

Classic Array Problems § Compute statistics (sum, mean, standard § § deviation, etc. ) of the values in an numeric array. Find the maximum (or minimum) value in an array. Search for a value in an array. Sort the values in an array. Others © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 20

Loading an Array § Before we solve a problem involving array, we need §

Loading an Array § Before we solve a problem involving array, we need § § § to first load values into the array! If you know the values before-hand, use array element initialization § Eg: int[] numbers = { 3, 7, -12, 8, 7 }; § Slide 9 of Chapter 10 If not, you need to read the values from the user § Use a loop to read in the values § Slides 6 -7 and 16 of Chapter 10 (If the array is large, the amount of data will be huge. We may need a file to store the data. We will learn how to read data from a file some other time. ) © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 21

Exercise 1: Summing an Array § Write a program Sum. Array. java to compute

Exercise 1: Summing an Array § Write a program Sum. Array. java to compute the sum § of all the values in an array containing type double values. Display the sum in 3 decimal places. Let’s do it into 2 phases: load the array with values first, then compute the sum. (Instead of accumulating the sum as we load the array. ) Size of array: 10 Enter 10 values: 5. 1 16 3. 2 1. 8 -4 12. 3 8 3. 3 -2 9. 1 The sum is 52. 800 § Download Sum. Array. java from course website, “Resources – Lectures” page. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 22

Exercise 2: Finding Maximum § Write a program Find. Max. java to find the

Exercise 2: Finding Maximum § Write a program Find. Max. java to find the largest value in an integer array. (Assume there is at least one element in the array. ) Size of array: 5 Enter 5 values: 10 -20 43 79 8 The largest value is 79 § Take home exercise: What if you want to report the index of the largest value, instead of the value itself? (This problem is not well-defined! Why? ) Size of array: 5 Enter 5 values: 10 -20 43 79 8 The largest value is at index 3 © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 23

Very Common Mistake #1 n Array Index Out of Range q Beware of Array.

Very Common Mistake #1 n Array Index Out of Range q Beware of Array. Index. Out. Of. Bounds. Exception. public static void main(String[] args) { int numbers = new int[10]; . . . for (int i=1; i<=numbers. length; i++) System. out. println(numbers[i]); } © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 24

Modular Programming Revisit n n “Modularize” Sum. Array. java and Find. Max. java so

Modular Programming Revisit n n “Modularize” Sum. Array. java and Find. Max. java so that the computation of sum or maximum is performed in a method. Call your new programs Sum. Array. Modular. java and Find. Max. Modular. java. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 25

Exercise 3: Coin Change n n n Download the file Ch 3 Coin. Change.

Exercise 3: Coin Change n n n Download the file Ch 3 Coin. Change. java from the course website, “Resources – Lectures”. Rewrite it using an array of coin denominations (int[] coins). Name your program Ch 10 Coin. Change. java. Modularize your program by writing a method compute. Coins(). q q What is its return type? Does it have any argument(s)? If so, what is/are the type(s) of its argument(s)? © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 26

Exercise 4: Array of Points (Take-home) (1/2) n n n Write a program Ch

Exercise 4: Array of Points (Take-home) (1/2) n n n Write a program Ch 10 Point. Array. java to create an array of Point objects, and find out which point in the array is furthest from the origin. If there are more than one such furthest point, output the smallest index among them. You may assume that the array contains at least one point. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 27

Exercise 4: Array of Points (Take-home) (2/2) n Sample output: Enter number of points:

Exercise 4: Array of Points (Take-home) (2/2) n Sample output: Enter number of points: 5 Enter coordinates for point #0: -2 -2 Enter coordinates for point #1: 1 4 Enter coordinates for point #2: 4 -3 Enter coordinates for point #3: 0 5 Enter coordinates for point #4: -1 1 The furthest point is at index 2 © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 28

Very Common Mistake #2 (1/2) n n When you have an array of objects,

Very Common Mistake #2 (1/2) n n When you have an array of objects, it’s very common to forget to instantiate the array’s objects. Programmers often instantiate the array itself and then think they’re done – that leads to java. lang. Null. Pointer. Exception. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 29

Very Common Mistake #2 (2/2) Point[] array = new Point[3]; array for (int i=0;

Very Common Mistake #2 (2/2) Point[] array = new Point[3]; array for (int i=0; i<array. length; i++) { null array[i]. set. Location(1, 2); null } There are no objects referred to by array[0], array[1], and array[2]! Corrected code: array null x 01 y 02 Point[] array = new Point[3]; for (int i=0; i<array. length; i++) { array[i] = new Point(); x 01 y 02 array[i]. set. Location(1, 2); } © CS 1101 (AY 2009 -2010 Semester 1) x 01 y 02 Week 8 - 30

Method main() (1/2) n n Now that we have learned array, let’s check out

Method main() (1/2) n n Now that we have learned array, let’s check out the main() method. Usual header for main() method: public static void main(String[] args) q n args is an array of String objects. Download Ch 10 Main. Demo. java: public class Ch 10 Main. Demo { public static void main(String[] args) { for (int i=0; i<args. length; i++) System. out. println("args[" + i + "]: " + args[i]); } } © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 31

Method main() (2/2) n This allows user to specify command line arguments when executing

Method main() (2/2) n This allows user to specify command line arguments when executing the program. java Ch 10 Main. Demo 10 ABC-D hello "Ice cream" n Output: args[0]: args[1]: args[2]: args[3]: © CS 1101 (AY 2009 -2010 Semester 1) 10 ABC-D hello Ice cream Week 8 - 32

Summary for Today n Characters and Strings q q n More String methods Patterns

Summary for Today n Characters and Strings q q n More String methods Patterns (regular expressions) Arrays q q q Syntax of one-dimensional array Creating and using an array Passing array into a method © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 33

Announcements/Things-to-do (1/2) n Complete the following q n Take-home lab #4 n n Ch

Announcements/Things-to-do (1/2) n Complete the following q n Take-home lab #4 n n Ch 10 Point. Array. java Deadline: 12 October 2009, Monday, 23: 59 hr To prepare for next lecture q q q We will continue with 2 -dimensional arrays and Array. List next week. Read Chapters 10 and 8 and their Power. Point files before you come for lecture. We will skip Map for Chapter 10, and Assertions for Chapter 8. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 34

Announcements/Things-to-do (2/2) n Sit-in Lab #2 q q q To be conducted during this

Announcements/Things-to-do (2/2) n Sit-in Lab #2 q q q To be conducted during this week’s discussion session. Please be punctual. Make-up lab will only be allowed if you miss the lab with valid reason and proof. Topics tested include everything up to Chapter 7. Sit-in lab #2 constitute 5% of your final grade. © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 35

End of File © CS 1101 (AY 2009 -2010 Semester 1) Week 8 -

End of File © CS 1101 (AY 2009 -2010 Semester 1) Week 8 - 36