cosc 236 section 101 - tripodlecture-notes.tripod.com/handouts/cosc236lecture12.pdfreview of quiz 11...

Post on 25-Oct-2020

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

COSC 236 Section 101Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Web Site

• You will always find the course material at:

http://www.class-notes.us or

http://www.class-notes.info or

http://www.lecture-notes.tripod.com

From this site you can click on the COSC-236 tab to download the PowerPoint lectures, the Quiz solutions and the Laboratory assignments.

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

2

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

3

Review of Quiz 11

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

4

Review of Quiz 11

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

5

The key points to understand from Quiz 11 are as follows:

1. The actual parameter in the calling program is a string that contains the Scanner

input entered by the user.

2. The actual parameter from the calling method is copied into the formal parameter

in the called method (this is the text to be reversed).

3. The three key concepts tested in Quiz 11:

a. Using String Method .toUpperCase() to convert the text to upper case

b. Setting up a for loop to count down from the last character (text.length()-1) to

the first character in the string

c. Using String Method .charAt(i) or .substring(i, i+1) to access a single character

in text and print it out using System.out.print(text.charAt(i));

Review of Quiz 11 (using text.charAt(i))

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

6

Review of Quiz 11 (using text.substing(i, i+1))

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

7

Review of Quiz 11

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

8

Factoring if/else code (pp. 247 – 249)• factoring: Extracting common/redundant code.

• Can reduce or eliminate redundancy from if/else code.

• Example:if (a == 1) {

System.out.println(a);x = 3;b = b + x;

} else if (a == 2) {System.out.println(a);x = 6;y = y + 10;b = b + x;

} else { // a == 3System.out.println(a);x = 9;b = b + x;

}

System.out.println(a);

x = 3 * a;

if (a == 2) {

y = y + 10;

}

b = b + x;

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

9

4.1 if/else statement (pp. 235 – 249)

Slide from last lectureUPDATE

4.3 Text Processing (pp. 261 – 270)

•Programmers commonly face problems that require them to create, edit, examine, and format text. • Collectively, we call these tasks text processing.• Text Processing: Editing and formatting strings of text.

• In this section:• We look in more detail at the char primitive type• Introduce a new command called System.out.printf. • Both of these tools are very useful for text-processing

tasks.

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

10

Type char (pp. 261-262)• char : A primitive type representing single characters.

• A String is stored internally as an array of char

String s = "Ali G.";

• It is legal to have variables, parameters, returns of type char• surrounded with apostrophes: 'a' or '4' or '\n' or '\''

char letter = 'P';

System.out.println(letter); // P

System.out.println(letter + " Diddy"); // P Diddy

index 0 1 2 3 4 5

value 'A' 'l' 'i' ' ' 'G' '.'

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

11

4.3 Text Processing (pp. 261 – 270)

The charAt method (p. 262)• The chars in a String can be accessed using the charAt method.

• charAt(n) accepts an int n index parameter and returns the char at that index

String food = "cookie";char firstLetter = food.charAt(0); // 'c'

System.out.println(firstLetter + " is for " + food);

• You can use a for loop to print or examine each character.

String major = "CSE";

for (int i = 0; i < major.length(); i++) { // output:

char c = major.charAt(i); // C

System.out.println(c); // S

} // E

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

12

4.3 Text Processing (pp. 261 – 270)

Comparing char values (p. 262)• You can compare chars with ==, !=, and other operators:

String word = console.next();

char last = word.charAt(word.length() - 1);

if (last == 's') {

System.out.println(word + " is plural.");

}

// prints the alphabet

for (char c = 'a'; c <= 'z'; c++) {

System.out.print(c);

}

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

13

4.3 Text Processing (pp. 261 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

14

4.3 Text Processing (pp. 261 – 270)

Differences between char and String (p. 262)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

15

4.3 Text Processing (pp. 261 – 270)

Differences between == and .equals (p. 262)

The == detects that they are not the same object – so == gives a falseThe .equals detects that they contain the same string – so .equals gives a true

Comparing strings (p. 262)• Relational operators such as < and == fail on objects.

Scanner console = new Scanner(System.in);

System.out.print("What is your name? ");

String name = console.next();

if (name == "Barney") {

System.out.println("I love you, you love me,");

System.out.println("We're a happy family!");

}

• This code will compile, but it will not print the song.

• == compares objects by references (seen later), so it often gives false even when two Strings have the same letters.

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

16

4.3 Text Processing (pp. 261 – 270)

The equals method (p. 262)• Objects are compared using a method named equals.

Scanner console = new Scanner(System.in);

System.out.print("What is your name? ");

String name = console.next();

if (name.equals("Barney")) {

System.out.println("I love you, you love me,");

System.out.println("We're a happy family!");

}

• Technically this is a method that returns a value of type boolean,the type used in logical tests.

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

17

4.3 Text Processing (pp. 261 – 270)

String test methods (p. 262)

String name = console.next();

if (name.startsWith("Prof")) {

System.out.println("When are your office hours?");

} else if (name.equalsIgnoreCase("STUART")) {

System.out.println("Let's talk about meta!");

}

Method Description

equals(str) whether two strings contain the same characters

equalsIgnoreCase(str) whether two strings contain the same characters, ignoring upper vs. lower case

startsWith(str) whether one contains other's characters at start

endsWith(str) whether one contains other's characters at end

contains(str) whether the given string is found within this one

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

18

4.3 Text Processing (pp. 261 – 270)

char vs. String (p. 262)• "h" is a String, but 'h' is a char (each has Unicode 104, but they are different)

• A String is an object; it contains methods.String s = "h";s = s.toUpperCase(); // "H"int len = s.length(); // 1char first = s.charAt(0); // 'H'

• A char is primitive; you can't call methods on it.char c = 'h';c = c.toUpperCase(); // ERRORs = s.charAt(0).toUpperCase(); // ERROR

• What is s + 1 ? What is c + 1 ? • What is s + s ? What is c + c ?

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

19

4.3 Text Processing (pp. 261 – 270)

s + 1 = “h1” c + 1 = 105s + s = “hh” c + c = 208

char vs. int (pp. 262-263)• Each char is mapped to an integer value internally

• Called an ASCII value

'A' is 65 'B' is 66 ' ' is 32'a' is 97 'b' is 98 '*' is 42

• Mixing char and int causes automatic conversion to int.'a' + 10 is 107, 'A' + 'A' is 130

• To convert an int into the equivalent char, type-cast it.(char) ('a' + 2) is 'c'

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

20

4.3 Text Processing (pp. 261 – 270)

Cumulative Text Algorithms (pp. 263-265)

• Cumulative algorithms accumulate a sum or a product• We saw these in last lecture for finding the sum and product of a

set of numbers

• We can also do accumulation algorithms with text• Count the number of times something appears in text

• How many times a character appears

• How many times an alphabetic letter appears

• How many times a number appears

• And many similar counting algorithms

• Concatenate characters to build up a stringCOSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

21

4.3 Text Processing (pp. 261 – 270)

Cumulative Text Algorithms (pp. 263-265)Method to count the number of times a character appears in a line of text:

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

22

4.3 Text Processing (pp. 261 – 270)

public static int count(String text, char c) {

int found = 0;

for (int i = 0; i < text.length(); i++) {

if (text.charAt(i) == c) {

found++;

}

}

return found;

}

Cumulative Text Algorithms (pp. 263-265)Some useful methods for text processing:

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

23

4.3 Text Processing (pp. 261 – 270)

Cumulative Text Algorithms (pp. 263-265)Method to count the number of alphabetic character that appear in a line of text:

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

24

4.3 Text Processing (pp. 261 – 270)

public static int countLetters(String phrase) {

int count = 0;

for (int i = 0; i < phrase.length(); i++) {

char ch = phrase.charAt(i);

if (Character.isLetter(ch)) {

count++;

}

}

return count;

}

Cumulative Text Algorithms (pp. 263-265)Method to do cumulative concatenation in order to reverse a line of text:

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

25

4.3 Text Processing (pp. 261 – 270)

public static String reverse(String phrase) {

String result = "";

for (int i = 0; i < phrase.length(); i++) {

result = phrase.charAt(i) + result;

}

return result;

}

Compare this algorithm to the algorithm we used in the Quiz 11 solution discussed at the beginning of today’s lecture.

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

26

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

27

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

28

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

29

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

30

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

31

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

32

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

33

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

34

4.3 Text Processing (pp. 261 – 270)

Formatting text with printf (pp. 265 – 270)System.out.printf("format string", parameters);

• A format string can contain placeholders to insert parameters:• %d integer• %f real number• %s string

• these placeholders are used instead of + concatenation

• Example:int x = 3;int y = -17;System.out.printf("x is %d and y is %d!\n", x, y);

// x is 3 and y is -17!

• printf does not drop to the next line unless you write \n

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

35

4.3 Text Processing (pp. 261 – 270)

printf width (pp. 265-270)• %Wd integer, W characters wide, right-aligned• %-Wd integer, W characters wide, left-aligned• %Wf real number, W characters wide, right-aligned• ...

for (int i = 1; i <= 3; i++) {for (int j = 1; j <= 10; j++) {

System.out.printf("%4d", (i * j));}System.out.println(); // to end the line

}

Output:1 2 3 4 5 6 7 8 9 102 4 6 8 10 12 14 16 18 203 6 9 12 15 18 21 24 27 30

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

36

4.3 Text Processing (pp. 261 – 270)

printf precision (pp. 265-270)• %.Df real number, rounded to D digits after decimal

• %W.Df real number, W chars wide, D digits after decimal

• %-W.Df real number, W wide (left-align), D after decimal

double gpa = 3.253764;

System.out.printf("your GPA is %.1f\n", gpa);

System.out.printf("more precisely: %8.3f\n", gpa);

Output:

your GPA is 3.3

more precisely: 3.254

8

3

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

37

4.3 Text Processing (pp. 261 – 270)

printf question (pp, 265-270)• Modify our Receipt program to better format its output.

• Display results in the format below, with $ and 2 digits after .

• Example log of execution:

How many people ate? 4

Person #1: How much did your dinner cost? 20.00

Person #2: How much did your dinner cost? 15

Person #3: How much did your dinner cost? 25.0

Person #4: How much did your dinner cost? 10.00

Subtotal: $70.00

Tax: $5.60

Tip: $10.50

Total: $86.10

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

38

4.3 Text Processing (pp. 261 – 270)

printf answer (partial) (pp. 265-270)// Calculates total owed, assuming 8% tax and 15% tip

public static void results(double subtotal) {

double tax = subtotal * .08;

double tip = subtotal * .15;

double total = subtotal + tax + tip;

// System.out.println("Subtotal: $" + subtotal);

// System.out.println("Tax: $" + tax);

// System.out.println("Tip: $" + tip);

// System.out.println("Total: $" + total);

System.out.printf("Subtotal: $%.2f\n", subtotal);

System.out.printf("Tax: $%.2f\n", tax);

System.out.printf("Tip: $%.2f\n", tip);

System.out.printf("Total: $%.2f\n", total);

}

}

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

39

4.3 Text Processing (pp. 261 – 270)

Catching Divide by Zero Errors (270-271)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

40

4.4 Conditional Execution (pp. 270 - 281)

• Because Java uses the IEEE standard for floating point numbers a divide by zero does not cause and error:• IEEE defines 0.0/0.0 as NaN (Not a Number)

• IEEE defines a positive number divided by zero as Infinity

• IEEE defines a negative number divided by zero as –Infinity

• However, IEEE does not specify what to do with integer divides by zero• Java will issue an exception (execution error) and stop running on a divide by

zero

• Java provides Try/Catch as one method to deal with exceptions

Catching Divide by Zero Errors (270-271)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

41

4.4 Conditional Execution (pp. 270 - 281)

Catching Divide by Zero Errors (270-271)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

42

4.4 Conditional Execution (pp. 270 - 281)

Try/Catch: Appendix p. 1118

Good Programming Practice (270-274)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

43

4.4 Conditional Execution (pp. 270 - 281)

• Good programming practice is to avoid execution errors• Check input values to be sure they are within limits

• Check preconditions before calling any method

• Check postconditions before exiting any methods

• Three different ways of checking• BEST: Check using Java conditionals (if/then/else)

• GOOD: Use Try/Catch to deal with exceptions

• FAIR: Have your program throw an exception when conditions are not met

• POOR: Don’t check and rely on Java exceptions

Good Programming Practice (270-274)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

44

4.4 Conditional Execution (pp. 270 - 281)

• Factorial method• Accepts an integer n and produces the factorial (1x2x3x4x … x(n-1)xn)

• Includes a test for negative n

• Throws an exception for negative n

• Three different ways of checking• BEST: Check for negative n before calling the method (if/then/else)

• GOOD: We could use Try/Catch to deal with exception

• FAIR: Allow the method to throw the exception on negative n

• POOR: Don’t check and in this case you will get an incorrect result for negative n

Factorial Method (270-274)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

45

4.4 Conditional Execution (pp. 270 - 281)

NOTE: A comma after the % token will format comas in the printout.

Factorial Method (270-274)

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

46

4.4 Conditional Execution (pp. 270 - 281)

Assignments for this week

1. Laboratory for Chapter 4 due Monday 10/20• IMPORTANT: When you email me your laboratory Word

Document, be sure it is all in one file

2. Wednesday we will review for Midterm 1 – look over all the quizzes in preparation.

3. Be sure to complete Quiz 12 before leaving class tonight• This is another program to write

• You must demonstrate the program to me before you leave lab

COSC 236 :Prof. M.A. Soderstrand Lecture 12 10/6/2014

47

top related