COSC 236 Section 101 Computer 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. 2
3
Review of Quiz 11 4
Review of Quiz 11 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)); 5
Review of Quiz 11 (using text.charat(i)) 6
Review of Quiz 11 (using text.substing(i, i+1)) 7
Review of Quiz 11 8
4.1 if/else statement (pp. 235 249) 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 == 3 System.out.println(a); x = 9; b = b + x; } Slide from last lecture UPDATE System.out.println(a); x = 3 * a; if (a == 2) { y = y + 10; } b = b + x; 9
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. 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."; index 0 1 2 3 4 5 value 'A' 'l' 'i' ' ' '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 11
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 12
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); } 13
Differences between char and String (p. 262) 14
Differences between == and.equals (p. 262) The == detects that they are not the same object so == gives a false The.equals detects that they contain the same string so.equals gives a true 15
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. 16
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. 17
String test methods (p. 262) Method equals(str) equalsignorecase(str) startswith(str) endswith(str) contains(str) Description whether two strings contain the same characters whether two strings contain the same characters, ignoring upper vs. lower case whether one contains other's characters at start whether one contains other's characters at end whether the given string is found within this one 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!"); } 18
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(); // 1 char first = s.charat(0); // 'H' A char is primitive; you can't call methods on it. char c = 'h'; c = c.touppercase(); s = s.charat(0).touppercase(); What is s + 1? What is c + 1? What is s + s? What is c + c? // ERROR // ERROR s + 1 = h1 c + 1 = 105 s + s = hh c + c = 208 19
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' 20
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 string 21
Cumulative Text Algorithms (pp. 263-265) Method to count the number of times a character appears in a line of text: 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; } 22
Cumulative Text Algorithms (pp. 263-265) Some useful methods for text processing: 23
Cumulative Text Algorithms (pp. 263-265) Method to count the number of alphabetic character that appear in a line of text: 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; } 24
Cumulative Text Algorithms (pp. 263-265) Method to do cumulative concatenation in order to reverse a line of text: 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. 25
Formatting text with printf (pp. 265 270) 26
Formatting text with printf (pp. 265 270) 27
Formatting text with printf (pp. 265 270) 28
Formatting text with printf (pp. 265 270) 29
Formatting text with printf (pp. 265 270) 30
Formatting text with printf (pp. 265 270) 31
Formatting text with printf (pp. 265 270) 32
Formatting text with printf (pp. 265 270) 33
Formatting text with printf (pp. 265 270) 34
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 35
printf width (pp. 265-270) %Wd %-Wd %Wf... integer, W characters wide, right-aligned integer, W characters wide, left-aligned 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 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 36
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 37
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 38
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); 39
4.4 Conditional Execution (pp. 270-281) Catching Divide by Zero Errors (270-271) 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 40
4.4 Conditional Execution (pp. 270-281) Catching Divide by Zero Errors (270-271) 41
4.4 Conditional Execution (pp. 270-281) Catching Divide by Zero Errors (270-271) Try/Catch: Appendix p. 1118 42
4.4 Conditional Execution (pp. 270-281) Good Programming Practice (270-274) 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 43
4.4 Conditional Execution (pp. 270-281) Good Programming Practice (270-274) 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 44
4.4 Conditional Execution (pp. 270-281) Factorial Method (270-274) NOTE: A comma after the % token will format comas in the printout. 45
4.4 Conditional Execution (pp. 270-281) Factorial Method (270-274) 46
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 47