CS& 141, Spring 2022
In Lecture 7 of CS 141 for Spring 2022, concepts related to if/else statements, cumulative algorithms, and strings are discussed. Credit is given to Marty Stepp and Stuart Reges for their contributions to the presentation slides. This session delves into the intricacies of conditional logic, algorithms that involve summing up results incrementally, and the manipulation and handling of textual data. Dive into a comprehensive exploration of these fundamental programming concepts in the context of this lecture.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
CS& 141, Spring 2022 Lecture 7: if/else, cumulative algorithms, Strings Thank you to Marty Stepp and Stuart Reges for parts of these slides 1
Exercise: BMR Write a program that produces output like the following: This program reads data for two people and computes their basal metabolic rate and burn rate. Basal Metabolic Rate Formula: male BMR = 4.54545 x (weight in lb) + 15.875 x (height in inches) - 5 x (age in years) + 5 Enter next person's information: height (in inches)? 73.5 weight (in pounds)? 230 age (in years)? 35 gender (enter 1 for male or 2 for female)? 1 female BMR = 4.54545 x (weight in lb) + 15.875 x (height in inches) - 5 x (age in years) - 161 Enter next person's information: height (in inches)? 71 weight (in pounds)? 220.5 age (in years)? 20 gender (enter 1 for male or 2 for female)? 2 BMR Burn Level Person #1 basal metabolic rate = 2042.3 high resting burn rate Person #2 basal metabolic rate = 1868.4 moderate resting burn rate below 12000 low 1200 to 2000 moderate above 2000 high 2
Development Strategy Writing a larger program like this can be intimidating so break it down into steps: Copy the expected output into a file and put each line in a println. 1. Add in code to read values from the user. Print them out to make sure they are correct. 2. Add in the computation for overall results 3. Divide your code into functions based on capturing structure and eliminating redundancy 4. 3
BMR: Step 1 Code 1 2 public class BMR { 3 public static void main(String[] args) { 4 System.out.println("This program reads data for two"); 5 System.out.println("people and computes their basal"); 6 System.out.println("metabolic rate and burn rate."); 7 System.out.println(); 8 9 System.out.println("Enter next person's information:"); 10 System.out.println("height (in inches)? 73.5"); 11 System.out.println("weight (in pounds)? 230"); 12 System.out.println("age (in years)? 35"); 13 System.out.println("gender (enter 1 for male or 2 for female)? 1"); 14 System.out.println(); 15 16 System.out.println("Enter next person's information:"); 17 System.out.println("height (in inches)? 71"); 18 System.out.println("weight (in pounds)? 220.5"); 19 System.out.println("age (in years)? 20"); 20 System.out.println("gender (enter 1 for male or 2 for female)? 2"); 21 System.out.println(); 22 23 System.out.println("Person #1 basal metabolic rate = 2042.3"); 24 System.out.println("high resting burn rate"); 25 System.out.println("Person #2 basal metabolic rate = 1868.4"); 26 System.out.println("moderate resting burn rate"); 27 } 28 } 4
BMR: Step 2 Code user input 1 import java.util.*; 2 3 public class BMR { 4 public static void main(String[] args) { 5 System.out.println("This program reads data for two"); 6 System.out.println("people and computes their basal"); 7 System.out.println("metabolic rate and burn rate."); 8 System.out.println(); 9 10 Scanner console = new Scanner(System.in); 11 12 System.out.println("Enter next person's information:"); 13 System.out.print("height (in inches)? "); 14 double height = console.nextDouble(); 15 System.out.print("weight (in pounds)? "); 16 double weight = console.nextDouble(); 17 System.out.print("age (in years)? "); 18 double age = console.nextDouble(); 19 System.out.print("gender (enter 1 for male or 2 for female, 3 for other)? "); 20 int gender = console.nextInt(); 21 System.out.println(); 22 (Continued on the next slide) 5
BMR: Step 2 Code user input ... 23 24 25 26 27 28 29 30 "); 31 32 33 34 35 36 37 38 39 40 41 42 } System.out.println("Enter next person's information:"); System.out.print("height (in inches)? "); double height2 = console.nextDouble(); System.out.print("weight (in pounds)? "); double weight2 = console.nextDouble(); System.out.print("age (in years)? "); double age2 = console.nextDouble(); System.out.print("gender (enter 1 for male or 2 for female, 3 for other)? int gender2 = console.nextInt(); System.out.println(); System.out.println("DEBUG: person 1: " + height + " " + weight + " " + age + " " + gender); System.out.println("DEBUG: person 2: " + height2 + " " + weight2 + " " + age2 + " " + gender2); System.out.println("Person #1 basal metabolic rate = 2042.3"); System.out.println("high resting burn rate"); System.out.println("Person #2 basal metabolic rate = 1868.4"); System.out.println("moderate resting burn rate"); } 6
BMR: Step 3 Code - Computation 1 import java.util.*; 2 3 public class BMR { 4 public static void main(String[] args) { 5 System.out.println("This program reads data for two"); 6 System.out.println("people and computes their basal"); 7 System.out.println("metabolic rate and burn rate."); 8 System.out.println(); 9 10 Scanner console = new Scanner(System.in); 11 12 System.out.println("Enter next person's information:"); 13 System.out.print("height (in inches)? "); 14 double height = console.nextDouble(); 15 System.out.print("weight (in pounds)? "); 16 double weight = console.nextDouble(); 17 System.out.print("age (in years)? "); 18 double age = console.nextDouble(); 19 System.out.print("gender (enter 1 for male or 2 for female, 3 for other)? "); 20 int gender = console.nextInt(); 21 System.out.println(); 22 23 System.out.println("Enter next person's information:"); 24 System.out.print("height (in inches)? "); 25 double height2 = console.nextDouble(); 26 System.out.print("weight (in pounds)? "); 27 double weight2 = console.nextDouble(); 28 System.out.print("age (in years)? "); 29 double age2 = console.nextDouble(); 30 System.out.print("gender (enter 1 for male or 2 for female, 3 for other)? "); 31 int gender2 = console.nextInt(); 32 System.out.println(); 7
BMR: Step 3 Code - Computation . . . 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 } double bmr = 4.54545 * weight + 15.875 * height - 5 * age; if(gender == 1) { bmr += 5; } else if (gender == 2) { bmr -= 161; } else { bmr -= 74; } double bmr2 = 4.54545 * weight2 + 15.875 * height2 - 5 * age2; if(gender2 == 1) { bmr2 += 5; } else if (gender2 == 2) { bmr2 -= 161; } else { bmr2 -= 74; } System.out.println("Person #1 basal metabolic rate = 2042.3"); System.out.println("high resting burn rate"); System.out.println("Person #2 basal metabolic rate = 1868.4"); System.out.println("moderate resting burn rate"); } 8
Dividing Code into Methods Create a function when: 1. You need to capture structure Write down a summary of what your program does; this is what should be in your main Example: print intro ask for person 1's data ask for person 2's data compute person 1 BMR compute person 2 BMR print results You need to capture redundancy Where is there repeated logic? 2. 9
BMR: Final Code import java.util.*; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class BMR { public static void main(String[] args) { intro(); Scanner console = new Scanner(System.in); double bmr1 = getPersonData(console); double bmr2 = getPersonData(console); printResults(1, bmr1); printResults(2, bmr2); } public static void intro() { System.out.println("This program reads data for two"); System.out.println("people and computes their basal"); System.out.println("metabolic rate and burn rate."); System.out.println(); } public static double getPersonData(Scanner console) { System.out.println("Enter next person's information:"); System.out.print("height (in inches)? "); double height = console.nextDouble(); System.out.print("weight (in pounds)? "); double weight = console.nextDouble(); System.out.print("age (in years)? "); double age = console.nextDouble(); System.out.print("gender (enter 1 for male or 2 for female, 3 for other)? "); int gender = console.nextInt(); System.out.println(); return computeBmr(weight, height, age, gender); } 10
BMR: Final Code . . . 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 public static double computeBmr(double weight, double height, double age, int gender) { double bmr = 4.54545 * weight + 15.875 * height - 5 * age; if(gender == 1) { bmr += 5; } else if (gender == 2) { bmr -= 161; } else { bmr -= 74; } return bmr; } public static void printResults(int number, double bmr) { System.out.println("Person #" + number + " basal metabolic rate = " + bmr); String rate = category(bmr); System.out.println("high resting burn rate"); } public static String category(double bmr) { String result = "high"; if(bmr < 1200) { result = "low"; } else if(bmr <= 2000) { result = "moderate"; } return result; } } 11
Adding many numbers How would you find the sum of all integers from 1-1000? // This may require a lot of typing int sum = 1 + 2 + 3 + 4 + ... ; System.out.println("The sum is " + sum); What if we want the sum from 1 - 1,000,000? Or the sum up to any maximum? How can we generalize the above code? 13
Cumulative sum loop int sum = 0; for (int i = 1; i <= 1000; i++) { sum = sum + i; } System.out.println("The sum is " + sum); cumulative sum: A variable that keeps a sum in progress and is updated repeatedly until summing is finished. The sum in the above code is an attempt at a cumulative sum. Cumulative sum variables must be declared outside the loops that update them, so that they will still exist after the loop. 14
Cumulative product This cumulative idea can be used with other operators: int product = 1; for (int i = 1; i <= 20; i++) { product = product * 2; } System.out.println("2 ^ 20 = " + product); How would we make the base and exponent adjustable? 15
Scanner and cumulative sum We can do a cumulative sum of user input: Scanner console = new Scanner(System.in); int sum = 0; for (int i = 1; i <= 100; i++) { System.out.print("Type a number: "); sum = sum + console.nextInt(); } System.out.println("The sum is " + sum); 16
Cumulative sum question Modify the Receipt program from earlier lectures. Prompt for how many people, and each person's dinner cost. Use static methods to structure the solution. 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? 30.0 Person #4: How much did your dinner cost? 10.00 Subtotal: $75.0 Tax: $6.0 Tip: $11.25 Total: $92.25 17
Strings string: An object storing a sequence of text characters. Unlike most other objects, a String is not created with new. String name = "text"; String name = expression; Examples: String name = "Marla Singer"; int x = 3; int y = 5; String point = "(" + x + ", " + y + ")"; 18
Objects (usage) object: An entity that contains data and behavior. data: variables inside the object behavior: methods inside the object You interact with the methods; the data is hidden in the object. A class is a type of objects. Constructing (creating) an object: TypeobjectName = new Type(parameters); Calling an object's method: objectName.methodName(parameters); 19
Indexes Characters of a string are numbered with 0-based indexes: String name = "Ultimate"; index character 0 U 1 l 2 t 3 i 4 m 5 a 6 t 7 e First character's index : 0 Last character's index : 1 less than the string's length The individual characters are values of type char (seen later) 20
String methods Method name Description indexOf(str) index where the start of the given string appears in this string (-1 if not found) number of characters in this string the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string a new string with all lowercase letters a new string with all uppercase letters length() substring(index1, index2) or substring(index1) toLowerCase() toUpperCase() These methods are called using the dot notation: String starz = "Yeezy & Hova"; System.out.println(starz.length()); // 12 21
String method examples // index 012345678901 String s1 = "Stuart Reges"; String s2 = "Marty Stepp"; System.out.println(s1.length()); // 12 System.out.println(s1.indexOf("e")); // 8 System.out.println(s1.substring(7, 10)); // "Reg" String s3 = s2.substring(1, 7); System.out.println(s3.toLowerCase()); // "arty s" Given the following string: // index 0123456789012345678901 String book = "Building Java Programs"; How would you extract the word "Java" ? 22
Modifying strings Methods like substring and toLowerCase build and return a new string, rather than modifying the current string. String s = "Aceyalone"; s.toUpperCase(); System.out.println(s); // Aceyalone To modify a variable's value, you must reassign it: String s = "Aceyalone"; s = s.toUpperCase(); System.out.println(s); // ACEYALONE 23
Strings as user input Scanner's next method reads a word of input as a String. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); name = name.toUpperCase(); System.out.println(name + " has " + name.length() + " letters and starts with " + name.substring(0, 1)); Output: What is your name? Nas NAS has 3 letters and starts with N The nextLine method reads a line of input as a String. System.out.print("What is your address? "); String address = console.nextLine(); 24
Strings question Write a program that reads two people's first names and suggests a name for their company Example Output: Founder 1 first name? Danielle Founder 2 first name? John On the west coast? yes Suggested company name: JODANI Founder 1 first name? Danielle Founder 2 first name? John On the west coast? n Suggested company name: DANIJO 26
The equals method 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("Lance")) { System.out.println("Pain is temporary."); System.out.println("Quitting lasts forever."); } Technically this is a method that returns a value of type boolean, the type used in logical tests. 27
String test methods Method Description equals(str) equalsIgnoreCase(str) 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 startsWith(str) endsWith(str) contains(str) whether one contains other's characters at end whether the given string is found within this one String name = console.next(); if(name.endsWith("Kweli")) { System.out.println("Pay attention, you gotta listen to hear."); } else if(name.equalsIgnoreCase("NaS")) { System.out.println("I never sleep 'cause sleep is the cousin of death."); } 28
Type char char : A primitive type representing single characters. Each character inside a String is stored as a char value. Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4' or '\n' or '\'' It is legal to have variables, parameters, returns of type char char letter = 'S'; System.out.println(letter); // S char values can be concatenated with strings. char initial = 'P'; System.out.println(initial + " Diddy"); // P Diddy 29
The charAt method The chars in a String can be accessed using the charAt method. String food = "cookie"; char firstLetter = food.charAt(0); // 'c' System.out.println(firstLetter + " is for " + food); System.out.println("That's good enough for me!"); You can use a for loop to print or examine each character. String major = "CS&"; for (int i = 0; i < major.length(); i++) { char c = major.charAt(i); System.out.println(c); } Output: C S & 30
char vs. String "h" is a String 'h' is a char (the two behave differently) 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' char is primitive; you can't call methods on it char c = 'h'; c = c.toUpperCase(); // ERROR: "cannot be dereferenced" What is s + 1 ? What is c + 1 ? What is s + s ? What is c + c ? 31
char vs. int All char values are assigned numbers internally by the computer, called ASCII values. Examples: 'A' is 65, 'a' is 97, 'B' is 66, 'b' is 98, ' ' is 32 '*' 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' 32
Comparing char values You can compare char values with relational operators: 'a' < 'b' and 'X' == 'X' and 'Q' != 'q' An example that prints the alphabet: for (char c = 'a'; c <= 'z'; c++) { System.out.print(c); } You can test the value of a string's character: String word = console.next(); if (word.charAt(word.length() - 1) == 's') { System.out.println(word + " is plural."); } 33
String/char question A Caesar cipher is a simple encryption where a message is encoded by shifting each letter by a given amount. e.g. with a shift of 3, A D, H K, X A, and Z C Write a program that reads a message from the user and performs a Caesar cipher on its letters: Your secret message: Brad thinks Angelina is cute Your secret key: 3 The encoded message: eudg wklqnv dqjholqd lv fxwh 34
Strings answer 1 // This program reads a message and a secret key from the user and // encrypts the message using a Caesar cipher, shifting each letter. import java.util.*; public class SecretMessage { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Your secret message: "); String message = console.nextLine(); message = message.toLowerCase(); System.out.print("Your secret key: "); int key = console.nextInt(); encode(message, key); } ... 35
Strings answer 2 // This method encodes the given text string using a Caesar // cipher, shifting each letter by the given number of places. public static void encode(String text, int shift) { System.out.print("The encoded message: "); for (int i = 0; i < text.length(); i++) { char letter = text.charAt(i); // shift only letters (leave other characters alone) if (letter >= 'a' && letter <= 'z') { letter = (char) (letter + shift); // may need to wrap around if (letter > 'z') { letter = (char) (letter - 26); } else if (letter < 'a') { letter = (char) (letter + 26); } } System.out.print(letter); } System.out.println(); } } 36
Formatting text with printf 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 38
printf width %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 39
printf precision %.Df %W.Df %-W.Df real number, W wide (left-align), D after decimal real number, rounded to D digits after decimal real number, W chars wide, D digits 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 3 8 40
printf question Modify our Receipt program to better format its output. Display results in the format below, with 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 41
printf answer (partial) ... // 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); } } 42
A deceptive problem... Write a method printLetters that prints each letter from a word separated by commas. For example, the call: printLetters("Atmosphere") should print: A, t, m, o, s, p, h, e, r, e 44
Flawed solutions public static void printLetters(String word) { for(int i = 0; i < word.length(); i++) { System.out.print(word.charAt(i) + ", "); } System.out.println(); // end line } Output: A, t, m, o, s, p, h, e, r, e, public static void printLetters(String word) { for(int i = 0; i < word.length(); i++) { System.out.print(", " + word.charAt(i)); } System.out.println(); // end line } Output: , A, t, m, o, s, p, h, e, r, e 45
Fence post analogy We print n letters but need only n - 1 commas. Similar to building a fence with wires separated by posts: If we use a flawed algorithm that repeatedly places a post + wire, the last post will have an extra dangling wire. for (length of fence) { place a post. place some wire. } 46
Fencepost loop Add a statement outside the loop to place the initial "post." Also called a fencepost loop or a "loop-and-a-half" solution. place a post. for (length of fence - 1) { place some wire. place a post. } 47
Fencepost method solution public static void printLetters(String word) { System.out.print(word.charAt(0)); for(int i = 1; i < word.length(); i++) { System.out.print(", " + word.charAt(i)); } System.out.println(); // end line } Alternate solution: Either first or last "post" can be taken out: public static void printLetters(String word) { for(int i = 0; i < word.length() - 1; i++) { System.out.print(word.charAt(i) + ", "); } int last = word.length() 1; System.out.println(word.charAt(last)); // end line } 48
Fencepost question Write a method printPrimes that prints all prime numbers up to a max. Example: printPrimes(50) prints 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 If the maximum is less than 2, print no output. To help you, write a method countFactors which returns the number of factors of a given integer. countFactors(20) returns 6 due to factors 1, 2, 4, 5, 10, 20. 49
Fencepost answer // Prints all prime numbers up to the given max. public static void printPrimes(int max) { if (max >= 2) { System.out.print("2"); for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { System.out.print(", " + i); } } System.out.println(); } } // Returns how many factors the given number has. public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { count++; // i is a factor of number } } return count; } 50