View
4
Download
0
Category
Preview:
Citation preview
CSS 161 Fundamentals of Compu3ng
Flow control (4) October 17, 2012
Instructor: Uma Murthy
Announcements and reminders Announcements
– HW 1 grades delayed – will be out today
– Website update – HW1 solu3on (check homeworks and solu3ons page)
– Lecture 7 slides (check updated schedule page) Reminders
– All homeworks will be due before class at 11am, unless otherwise specified
– Prac3ce using Prac3ce it, self-‐test exercises, and programming exercises
– Midterm 1 on Wed, Oct 24
CSS 161: Fundamentals of Compu3ng 2
Outline today
• Review loops • Complete Chapter 3
• Do problems from book and Prac3ce it
CSS 161: Fundamentals of Compu3ng 3
Acknowledgments
• A subset of the following slides have been either directly taken from or derived from the supplements of the book: Building Java Programs: A Back to Basics Approach, 2nd edi(on by Stuart Reges and Marty Stepp
hVp://www.buildingjavaprograms.com/supplements.shtml
CSS 161: Fundamentals of Compu3ng 4
Review
• Boolean expressions – Short circuit evalua3on – Side-‐effects of Boolean expressions – Boolean expressions outside of condi3onals and loops
– Comparing Strings
CSS 161: Fundamentals of Compu3ng 5
Comparing Strings
• Comparison operators only work on primi%ve types – boolean, char, byte, short, int, long, float, double
• To compare other types, need other methods – compareTo() – equals() – equalsIgnoreCase() [for Strings only]
CSS 161: Fundamentals of Compu3ng 6
Comparing Strings example
String s1 = "tintin"; String s2 = "snowy"; String s3 = "Tintin";
System.out.println(s1.equals(s2)); System.out.println(s1.equals("tintin")); System.out.println(s1.equals(s3)); System.out.println(s1.equalsIgnoreCase(s3)); System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s1)); System.out.println(s2.compareTo("snowy"));
CSS 161: Fundamentals of Compu3ng 7
Comparing Strings example String s1 = "tintin"; String s2 = "snowy"; String s3 = "Tintin";
System.out.println(s1.equals(s2)); System.out.println(s1.equals("tintin")); System.out.println(s1.equals(s3)); System.out.println(s1.equalsIgnoreCase(s3)); System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s1)); System.out.println(s2.compareTo("snowy"));
false
true
false
true
1
-‐1
0
CSS 161: Fundamentals of Compu3ng 8
Loops
• Mechanism for repea3ng block of statements – Do we know how many 3mes to repeat?
– Do we want to execute at least once? • 3 types of loops:
while (boolean expression) statement
do statement while (boolean_expression)
for (initialization; stop_condition; update) statement
CSS 161: Fundamentals of Compu3ng 9
Loops
• Loops in Java are similar to those in other high-‐level languages
• Java has three types of loop statements: the while, the do-while, and the for statements – The code that is repeated in a loop is called the body of the loop
– Each repe33on of the loop body is called an itera%on of the loop
3-‐10 CSS 161: Fundamentals of
Compu3ng
while (Boolean_Expression) Statement Or while (Boolean_Expression) { Statement_1 Statement_2
Statement_Last }
while Syntax
. . .
3-‐11 CSS 161: Fundamentals of
Compu3ng
do Statement while (Boolean_Expression); Or do { Statement_1 Statement_2
Statement_Last } while (Boolean_Expression);
do-while Syntax
. . .
3-‐12 CSS 161: Fundamentals of
Compu3ng
The for loop
The for Statement Syntax
for (Initializing; Boolean_Expression; Update) Body
• The Body may consist of a single statement or a list of statements enclosed in a pair of braces ({ })
• Note that the three control expressions are separated by two, not three, semicolons
• Note that there is no semicolon aeer the closing parenthesis at the beginning of the loop
3-‐14 CSS 161: Fundamentals of
Compu3ng
for loop syntax for (ini(aliza(on; test; update) { statement; statement; ... statement; }
– Perform ini(aliza(on once.
– Repeat the following: • Check if the test is true. If not, stop. • Execute the statements.
• Perform the update.
body
header
Seman3cs of the for Statement
3-‐16 CSS 161: Fundamentals of
Compu3ng
Repe33on with for loops
• So far, repea3ng a statement is redundant: System.out.println("Homer says:"); System.out.println("I am so smart"); System.out.println("I am so smart"); System.out.println("I am so smart"); System.out.println("I am so smart"); System.out.println("S-M-R-T... I mean S-M-A-R-T");
• Java's for loop statement performs a task many 3mes. System.out.println("Homer says:");
for (int i = 1; i <= 4; i++) { // repeat 4 times System.out.println("I am so smart"); }
System.out.println("S-M-R-T... I mean S-M-A-R-T");
Ini3aliza3on for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); }
• Tells Java what variable to use in the loop – Performed once as the loop begins
– The variable is called a loop counter
• can use any name, not just i
• can start at any value, not just 1
Test for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); }
• Tests the loop counter variable against a limit
– Uses comparison operators:
< less than <= less than or equal to
> greater than
>= greater than or equal to
Repe33on over a range System.out.println("1 squared = " + 1 * 1); System.out.println("2 squared = " + 2 * 2); System.out.println("3 squared = " + 3 * 3); System.out.println("4 squared = " + 4 * 4); System.out.println("5 squared = " + 5 * 5); System.out.println("6 squared = " + 6 * 6);
– Intui3on: "I want to print a line for each number from 1 to 6"
• The for loop does exactly that! for (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i)); }
– "For each integer i from 1 through 6, print ..."
Loop walkthrough
for (int i = 1; i <= 4; i++) { System.out.println(i + " squared = " + (i * i)); } System.out.println("Whoo!");
Output:
1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 Whoo!
1
1
2
2
3
3
4
4
5
5
Increment and decrement shortcuts to increase or decrease a variable's value by 1
Shorthand Equivalent longer version variable++; variable = variable + 1; variable--; variable = variable - 1;
int x = 2; x++; // x = x + 1; // x now stores 3
double gpa = 2.5; gpa--; // gpa = gpa - 1; // gpa now stores 1.5
Modify-‐and-‐assign
shortcuts to modify a variable's value
Shorthand Equivalent longer version variable += value; variable = variable + value; variable -= value; variable = variable - value; variable *= value; variable = variable * value; variable /= value; variable = variable / value; variable %= value; variable = variable % value;
x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;
The Comma in for Statements
• A for loop can contain mul3ple ini3aliza3on ac3ons separated with commas – Use cau3on when combining a declara3on with mul3ple ac3ons
• A for loop can contain mul3ple update ac3ons, separated with commas, also – It is even possible to eliminate the loop body in this way
• However, a for loop can contain only one Boolean expression to test for ending the loop
3-‐24 CSS 161: Fundamentals of
Compu3ng
Infinite Loops
• A while, do-while, or for loop should be designed so that the Boolean expression is changed in a way that eventually makes it false, and terminates the loop
• If the Boolean expression remains true, then the loop will run forever, resul3ng in an infinite loop – Loops that check for equality or inequality (== or !=) are especially prone to this error and should be avoided if possible
3-‐25 CSS 161: Fundamentals of
Compu3ng
Nested Loops
• Loops can be nested, just like other Java structures – When nested, the inner loop iterates from beginning to end for each
single itera3on of the outer loop
int rowNum, columnNum; for (rowNum = 1; rowNum <=3; rowNum++) { for (columnNum = 1; columnNum <=2; columnNum++) System.out.print(" row " + rowNum + " column " + columnNum); System.out.println(); }
3-‐26 CSS 161: Fundamentals of
Compu3ng
Algorithms and Pseudocode
• The hard part of solving a problem with a computer program is coming up with the underlying solu3on method
• An algorithm is a set of precise instruc3ons that lead to a solu3on – An algorithm is normally wriVen in pseudocode, which is a mixture of programming language and a human language, like English
– Pseudocode must be precise and clear – However, pseudocode is much less rigid than code
3-‐27 CSS 161: Fundamentals of
Compu3ng
Example: Drawing complex figures • Use nested for loops to produce the following output.
• Why draw ASCII art? – Real graphics require a lot of finesse – ASCII art has complex paVerns – Can focus on the algorithms
#================# | <><> | | <>....<> | | <>........<> | |<>............<>| |<>............<>| | <>........<> | | <>....<> | | <><> | #================#
Development strategy • Recommenda3ons for managing complexity: 1. Design the program (think about steps or methods needed -‐ pseudocode).
• write an English descrip3on of steps required • use this descrip3on to decide the methods
2. Create a table of paVerns of characters • use table to write your for loops
#================# | <><> | | <>....<> | | <>........<> | |<>............<>| |<>............<>| | <>........<> | | <>....<> | | <><> | #================#
1. Pseudo-‐code
• pseudo-‐code: An English descrip3on of an algorithm.
• Example: Drawing a 12 wide by 7 tall box of stars
print 12 stars. for (each of 5 lines) {
print a star.
print 10 spaces.
print a star.
}
print 12 stars.
************ * * * * * * * * * * ************
Pseudo-‐code algorithm 1. Line
• # , 16 =, # 2. Top half
• | • spaces (decreasing) • <> • dots (increasing) • <> • spaces (same as above) • |
3. BoVom half (top half upside-‐down) 4. Line
• # , 16 =, #
#================# | <><> | | <>....<> | | <>........<> | |<>............<>| |<>............<>| | <>........<> | | <>....<> | | <><> | #================#
Methods from pseudocode public class Mirror { public static void main(String[] args) { line(); topHalf(); bottomHalf(); line(); }
public static void topHalf() { for (int line = 1; line <= 4; line++) { // contents of each line } }
public static void bottomHalf() { for (int line = 1; line <= 4; line++) { // contents of each line } }
public static void line() { // ... } }
2. Tables • A table for the top half:
– Compute spaces and dots expressions from line number
line spaces dots
1 6 0
2 4 4
3 2 8
4 0 12
line spaces line * -2 + 8 dots 4 * line - 4
1 6 6 0 0
2 4 4 4 4
3 2 2 8 8
4 0 0 12 12
#================# | <><> | | <>....<> | | <>........<> | |<>............<>| |<>............<>| | <>........<> | | <>....<> | | <><> | #================#
3. Wri3ng the code • Useful ques3ons about the top half:
– What methods? (think structure and redundancy)
– Number of (nested) loops per line? #================# | <><> | | <>....<> | | <>........<> | |<>............<>| |<>............<>| | <>........<> | | <>....<> | | <><> | #================#
Par3al solu3on // Prints the expanding pattern of <> for the top half of the
figure. public static void topHalf() { for (int line = 1; line <= 4; line++) { System.out.print("|");
for (int space = 1; space <= (line * -2 + 8); space++) { System.out.print(" "); }
System.out.print("<>");
for (int dot = 1; dot <= (line * 4 - 4); dot++) { System.out.print("."); }
System.out.print("<>");
for (int space = 1; space <= (line * -2 + 8); space++) { System.out.print(" "); }
System.out.println("|"); } }
The break and continue Statements
• The break statement consists of the keyword break followed by a semicolon – When executed, the break statement ends the nearest
enclosing switch or loop statement • The continue statement consists of the keyword continue followed by a semicolon – When executed, the continue statement ends the current
loop body itera3on of the nearest enclosing loop statement – Note that in a for loop, the continue statement transfers
control to the update expression
• When loop statements are nested, remember that any break or con3nue statement applies to the innermost, containing loop statement
3-‐36 CSS 161: Fundamentals of
Compu3ng
The Labeled break Statement
• There is a type of break statement that, when used in nested loops, can end any containing loop, not just the innermost loop
• If an enclosing loop statement is labeled with an Iden%fier, then the following version of the break statement will exit the labeled loop, even if it is not the innermost enclosing loop: break someIdentifier;
• To label a loop, simply precede it with an Iden%fier and a colon: someIdentifier:
3-‐37 CSS 161: Fundamentals of
Compu3ng
The exit Statement
• A break statement will end a loop or switch statement, but will not end the program
• The exit statement will immediately end the program as soon as it is invoked: System.exit(0);
• The exit statement takes one integer argument – By tradi3on, a zero argument is used to indicate a normal ending of the program
3-‐38 CSS 161: Fundamentals of
Compu3ng
Loop Bugs
• The two most common kinds of loop errors are unintended infinite loops and off-‐by-‐one errors – An off-‐by-‐one error is when a loop repeats the loop body one too many or one too few 3mes
• This usually results from a carelessly designed Boolean test expression
– Use of == in the controlling Boolean expression can lead to an infinite loop or an off-‐by-‐one error
• This sort of tes3ng works only for characters and integers, and should never be used for floa3ng-‐point
3-‐39 CSS 161: Fundamentals of
Compu3ng
Tracing Variables
• Tracing variables involves watching one or more variables change value while a program is running
• Many IDEs have a built-‐in Debugging u3lity that allows variables to be traced
• Another way to trace variables is to insert temporary output statements in a program System.out.println("n = " + n); // Tracing n – When the error is found and corrected, the trace statements can
simply be commented out
• A good way to test your program is to manually plug-‐in values and walk through your code – Common prac3ce in interviews
3-‐40 CSS 161: Fundamentals of
Compu3ng
General Debugging Techniques (1) • Examine the system as a whole – don’t assume the bug occurs in one par3cular place – Manually tracing helps significantly and is good prac%ce for exams and interviews
• Try different test cases and check the input values
3-‐41 CSS 161: Fundamentals of
Compu3ng
General Debugging Techniques (2) • Comment out blocks of code to narrow down the offending code
• Check common pinalls
• Take a break and come back later • DO NOT make random changes just hoping that the change will fix the problem!
3-‐42 CSS 161: Fundamentals of
Compu3ng
Debugging Example (1 of 9) • The following code is supposed to present a menu and get user input un3l either ‘a’ or ‘b’ is entered.
3-‐43 CSS 161: Fundamentals of
Compu3ng
String s = ""; char c = ' '; Scanner keyboard = new Scanner(System.in);
do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s.toLowerCase(); c = s.substring(0,1); } while ((c != 'a') || (c != 'b'));
Debugging Example (2 of 9)
• Using the “random change” debugging technique we might try to change the data type of c to String, to make the types match
• This results in more errors since the rest of the code treats c like a char
3-‐44 CSS 161: Fundamentals of
Compu3ng
Result: Syntax error:
c = s.substring(0,1); : incompatible types found: java.lang.String required: char
Debugging Example (3 of 9) • First problem: substring returns a String, use charAt to get the first character:
3-‐45 CSS 161: Fundamentals of
Compu3ng
String s = ""; char c = ' '; Scanner keyboard = new Scanner(System.in);
do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s.toLowerCase(); c = s.charAt(0); } while ((c != 'a') || (c != 'b'));
Now the program compiles, but it is stuck in an infinite loop. Employ tracing:
Debugging Example (4 of 9)
3-‐46 CSS 161: Fundamentals of
Compu3ng
do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); System.out.println("String s = " + s); s.toLowerCase(); System.out.println("Lowercase s = " + s); c = s.charAt(0); System.out.println("c = " + c); } while ((c != 'a') || (c != 'b'));
Sample output: Enter 'A' for option A or 'B' for option B. A String s = A Lowercase s = A c = A Enter 'A' for option A or 'B' for option B.
From tracing we can see that the string is never changed to lowercase. Reassign the lowercase string back to s.
Debugging Example (5 of 9) • The following code is supposed to present a menu and get user input un3l either ‘a’ or ‘b’ is entered.
3-‐47 CSS 161: Fundamentals of
Compu3ng
do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); } while ((c != 'a') || (c != 'b'));
However, it’s still stuck in an infinite loop. What to try next?
Debugging Example (6 of 9) • Could try the following “patch”
3-‐48 CSS 161: Fundamentals of
Compu3ng
do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); if ( c == 'a') break; if (c == 'b')
break; } while ((c != 'a') || (c != 'b'));
This works, but it is ugly! Considered a coding atrocity, it doesn’t fix the underlying problem. The boolean condition after the while loop has also become meaningless. Try more tracing:
Debugging Example (7 of 9)
3-‐49 CSS 161: Fundamentals of
Compu3ng
do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); System.out.println("c != 'a' is " + (c != 'a')); System.out.println("c != 'b' is " + (c != 'b')); System.out.println("(c != 'a') || (c != 'b')) is "
+ ((c != 'a') || (c != 'b'))); } while ((c != 'a') || (c != 'b'));
Sample output: Enter 'A' for option A or 'B' for option B. A c != 'a' is false c != 'b' is true (c != 'a') || (c != 'b')) is true
From the trace we can see that the loop’s boolean expression is true because c cannot be not equal to ‘a’ and not equal to ‘b’ at the same time.
Debugging Example (8 of 9) • Fix: We use && instead of ||
3-‐50 CSS 161: Fundamentals of
Compu3ng
do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); } while ((c != 'a') && (c != 'b'));
Debugging Example (9 of 9) • Even beVer: Declare a boolean variable to control the do-‐while loop. This makes it clear when the loop exits if we pick a meaningful variable name.
3-‐51 CSS 161: Fundamentals of
Compu3ng
boolean invalidKey; do { System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); if (c == 'a')
invalidKey = false; else if (c == 'b')
invalidKey = false; else
invalidKey = true; } while (invalidKey);
Preven3ve Coding
• Incremental Development – Write a liVle bit of code at a 3me and test it before moving on
• Code Review – Have others look at your code
• Pair Programming – Programming in a team, one typing while the other watches, and periodically switch roles
3-‐52 CSS 161: Fundamentals of
Compu3ng
Loops prac3ce
• See conversa3on on discussion board on catalyst
53 CSS 161: Fundamentals of Compu3ng
Asser3on Checks
• An asser%on is a sentence that says (asserts) something about the state of a program – An asser3on must be either true or false, and should be true if a
program is working properly – Asser3ons can be placed in a program as comments
• Java has a statement that can check if an asser3on is true assert Boolean_Expression; – If asser3on checking is turned on and the Boolean_Expression
evaluates to false, the program ends, and outputs an asser%on failed error message
– Otherwise, the program finishes execu3on normally
3-‐54 CSS 161: Fundamentals of
Compu3ng
Asser3on Checks
• A program or other class containing asser3ons is compiled in the usual way
• Aeer compila3on, a program can run with asser3on checking turned on or turned off – Normally a program runs with asser3on checking turned off
• In order to run a program with asser3on checking turned on, use the following command (using the actual ProgramName): java –enableassertions ProgramName
3-‐55 CSS 161: Fundamentals of
Compu3ng
Recommended