CSS 161 Fundamentals of Compu3ng Flow control, Debugging, - - PowerPoint PPT Presentation

css 161 fundamentals of compu3ng flow control debugging
SMART_READER_LITE
LIVE PREVIEW

CSS 161 Fundamentals of Compu3ng Flow control, Debugging, - - PowerPoint PPT Presentation

CSS 161 Fundamentals of Compu3ng Flow control, Debugging, Classes October 29, 2012 Instructor: Uma Murthy Announcements and reminders Announcements Quizzes


slide-1
SLIDE 1

CSS ¡161 ¡ Fundamentals ¡of ¡Compu3ng ¡ Flow ¡control, ¡Debugging, ¡Classes ¡

October ¡29, ¡2012 ¡

Instructor: ¡Uma ¡Murthy ¡

slide-2
SLIDE 2

Announcements ¡and ¡reminders ¡

Announcements ¡

– Quizzes ¡(see ¡forthcoming ¡slide) ¡ ¡ – Late ¡days ¡status ¡maintained ¡on ¡gradebook ¡

Reminders ¡

– Homework ¡4 ¡due ¡midnight ¡Wednesday, ¡October ¡31 ¡

2 ¡

slide-3
SLIDE 3

Late ¡days ¡on ¡gradebook ¡

3 ¡

Indicates the number of late days taken, ranging from 0 to 3

slide-4
SLIDE 4

Quizzes ¡

  • Begin ¡next ¡week ¡
  • Tenta3ve ¡schedule ¡and ¡topics: ¡

– 11/5: ¡condi3onal ¡statements ¡and ¡loops ¡ ¡ – 11/14: ¡Classes, ¡I/O ¡ – 11/28: ¡Arrays ¡

  • Mechanical ¡ques3ons ¡

– Short ¡answer, ¡output, ¡tracing, ¡etc. ¡

4 ¡

slide-5
SLIDE 5

Outline ¡today ¡

  • Definite ¡(for) ¡and ¡indefinite ¡(while,

do-while) ¡loops ¡

  • Pseudocode ¡and ¡nested ¡loops ¡example ¡
  • Fencepost ¡analogy ¡
  • Wrap ¡up ¡debugging ¡
  • Review ¡methods ¡
  • Parameterized ¡methods ¡

5 ¡

slide-6
SLIDE 6

Definite ¡and ¡indefinite ¡loops ¡

6 ¡

slide-7
SLIDE 7

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: ¡
  • for (initialization; stop_condition; update)

statement

  • while (boolean expression)

statement

  • do

statement while (boolean_expression)

7 ¡

slide-8
SLIDE 8

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-­‑8 ¡

slide-9
SLIDE 9

Categories ¡of ¡loops ¡

  • definite ¡loop: ¡Executes ¡a ¡known ¡number ¡of ¡3mes. ¡

– for ¡loops ¡are ¡definite ¡loops. ¡

  • Print ¡"hello" ¡10 ¡3mes. ¡
  • Find ¡all ¡the ¡prime ¡numbers ¡up ¡to ¡an ¡integer ¡n. ¡
  • Print ¡each ¡odd ¡number ¡between ¡5 ¡and ¡127. ¡
  • indefinite ¡loop: ¡One ¡where ¡the ¡number ¡of ¡3mes ¡its ¡

body ¡repeats ¡is ¡not ¡known ¡in ¡advance: ¡ ¡

– while and ¡do-while loops ¡are ¡indefinite ¡loops ¡

  • Prompt ¡the ¡user ¡un3l ¡they ¡type ¡a ¡non-­‑nega3ve ¡number. ¡
  • Print ¡random ¡numbers ¡un3l ¡a ¡prime ¡number ¡is ¡printed. ¡
  • Repeat ¡un3l ¡the ¡user ¡has ¡types ¡"q" ¡to ¡quit. ¡

9 ¡

slide-10
SLIDE 10

for(initialization; Boolean_Expression; update) Statement for(initialization; Boolean_Expression; update) { Statement_1 Statement_2 Statement_Last }

for ¡Syntax ¡

. ¡. ¡. ¡

3-­‑10 ¡

slide-11
SLIDE 11

for ¡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

11 ¡

slide-12
SLIDE 12

while (Boolean_Expression) Statement ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡Or ¡ while (Boolean_Expression) { Statement_1 Statement_2 Statement_Last }

while ¡Syntax ¡

. ¡. ¡. ¡

3-­‑12 ¡

slide-13
SLIDE 13

The ¡while ¡loop ¡

  • while ¡loop: ¡Repeatedly ¡executes ¡its ¡

body ¡as ¡long ¡as ¡a ¡logical ¡test ¡is ¡true. ¡

  • Example: ¡

int num = 1; // initialization

while (num <= 200) { // test System.out.print(num + " "); num = num * 2; // update } // output: 1 2 4 8 16 32 64 128 ¡

13 ¡

slide-14
SLIDE 14

do Statement while (Boolean_Expression); ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡Or ¡ do { Statement_1 Statement_2 Statement_Last } while (Boolean_Expression);

do-while ¡Syntax ¡

. ¡. ¡. ¡

3-­‑14 ¡

slide-15
SLIDE 15

The ¡do/while ¡loop ¡

  • do/while ¡loop: ¡Performs ¡its ¡test ¡at ¡the ¡end ¡of ¡each ¡
  • repe33on. ¡

– Guarantees ¡that ¡the ¡loop's ¡{} ¡body ¡will ¡run ¡at ¡least ¡once. ¡

//Example: prompt until correct password is typed String phrase; do { System.out.print("Type your password: "); phrase = console.next(); } while (!phrase.equals("abracadabra"));

15 ¡

slide-16
SLIDE 16

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 ¡wrieen ¡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-­‑16 ¡

slide-17
SLIDE 17

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-­‑17 ¡

slide-18
SLIDE 18

Example: ¡Drawing ¡complex ¡figures ¡

  • Use ¡nested ¡for ¡loops ¡to ¡produce ¡the ¡

following ¡output. ¡

+------+ |\..../| | \../ | | \/ | | /\ | | /..\ | |/....\| +------+

18 ¡

slide-19
SLIDE 19

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 ¡paeerns ¡of ¡characters ¡
  • use ¡table ¡to ¡write ¡your ¡for ¡loops ¡

+------+ |\..../| | \../ | | \/ | | /\ | | /..\ | |/....\| +------+

19 ¡

slide-20
SLIDE 20
  • 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. ¡

************ * * * * * * * * * * ************

20 ¡

slide-21
SLIDE 21

Pseudo-­‑code ¡algorithm ¡

  • 1. ¡Line ¡
  • + ¡, ¡6 ¡-, ¡+
  • 2. ¡Top ¡half ¡
  • |
  • spaces ¡(increasing) ¡
  • \
  • dots ¡(decreasing) ¡
  • /
  • spaces ¡(same ¡as ¡above) ¡
  • |
  • 3. ¡Boeom ¡half ¡(top ¡half ¡upside-­‑down) ¡
  • 4. ¡Line ¡
  • + ¡, ¡6 ¡-, ¡+

+------+ |\..../| | \../ | | \/ | | /\ | | /..\ | |/....\| +------+

21 ¡

slide-22
SLIDE 22

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 <= 3; line++) { // contents of each line } } public static void bottomHalf() { for (int line = 1; line <= 3; line++) { // contents of each line } } public static void line() { // ... } }

+------+ |\..../| | \../ | | \/ | | /\ | | /..\ | |/....\| +------+

22 ¡

slide-23
SLIDE 23
  • 2. ¡Tables

¡

  • A ¡table ¡for ¡the ¡top ¡half: ¡

– Compute ¡spaces ¡and ¡dots ¡expressions ¡from ¡line ¡number ¡

line spaces dots 1 4 2 1 2 3 2

+------+ |\..../| | \../ | | \/ | | /\ | | /..\ | |/....\| +------+

23 ¡

slide-24
SLIDE 24
  • 2. ¡Tables

¡

  • A ¡table ¡for ¡the ¡top ¡half: ¡

– Compute ¡spaces ¡and ¡dots ¡expressions ¡from ¡line ¡number ¡

line spaces

line - 1

dots

  • 2 * line + 6

1 4 4 2 1 1 2 2 3 2 2

+------+ |\..../| | \../ | | \/ | | /\ | | /..\ | |/....\| +------+

24 ¡

slide-25
SLIDE 25
  • 3. ¡Wri3ng ¡the ¡code

¡

  • Useful ¡ques3ons ¡about ¡the ¡top ¡half: ¡

– What ¡methods? ¡(think ¡structure ¡and ¡redundancy) ¡ – Number ¡of ¡(nested) ¡loops ¡per ¡line? ¡

+------+ |\..../| | \../ | | \/ | | /\ | | /..\ | |/....\| +------+

25 ¡

slide-26
SLIDE 26

Par3al ¡solu3on ¡

// Prints the reducing pattern of \/ for the top half of the figure. public static void topHalf() { for (int line = 1; line <= 3; line++) { System.out.print("|"); for (int space = 1; space <= (line - 1); space++) { System.out.print(" "); } System.out.print(”\\"); for (int dot = 1; dot <= (-2 * line + 6); dot++) { System.out.print("."); } System.out.print(”/"); for (int space = 1; space <= (line - 1); space++) { System.out.print(" "); } System.out.println("|"); } }

26 ¡

slide-27
SLIDE 27

A ¡decep3ve ¡problem... ¡

  • Write ¡a ¡method ¡printNumbers ¡that ¡prints ¡

each ¡number ¡from ¡1 ¡to ¡a ¡given ¡maximum, ¡ separated ¡by ¡commas. ¡ For ¡example, ¡the ¡call: ¡

printNumbers(5)

¡should ¡print: ¡

1, 2, 3, 4, 5

27 ¡

slide-28
SLIDE 28

Flawed ¡solu3ons ¡

  • public static void printNumbers(int max) {

for (int i = 1; i <= max; i++) { System.out.print(i + ", "); } System.out.println(); // to end the line of output }

– Output ¡from ¡printNumbers(5): ¡1, 2, 3, 4, 5,

  • public static void printNumbers(int max) {

for (int i = 1; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line of output }

– Output ¡from ¡printNumbers(5): ¡, 1, 2, 3, 4, 5

28 ¡

slide-29
SLIDE 29

Fence ¡post ¡analogy ¡

  • We ¡print ¡n ¡numbers ¡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. ¡ ¡} ¡

29 ¡

slide-30
SLIDE 30

Fencepost ¡loop ¡

  • Add ¡a ¡statement ¡outside ¡the ¡loop ¡to ¡place ¡the ¡

ini3al ¡"post." ¡

– Also ¡called ¡a ¡fencepost ¡loop ¡or ¡a ¡"loop-­‑and-­‑a-­‑half" ¡

  • solu3on. ¡

¡place ¡a ¡post. ¡ ¡for ¡(length ¡of ¡fence ¡-­‑ ¡1) ¡{ ¡ ¡ ¡ ¡ ¡ ¡place ¡some ¡wire. ¡ ¡ ¡ ¡ ¡ ¡place ¡a ¡post. ¡ ¡} ¡

30 ¡

slide-31
SLIDE 31

Fencepost ¡method ¡solu3on ¡

public static void printNumbers(int max) { System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line }

  • Alternate ¡solu3on: ¡Either ¡first ¡or ¡last ¡"post" ¡can ¡be ¡taken ¡out:

public static void printNumbers(int max) { for (int i = 1; i <= max - 1; i++) { System.out.print(i + ", "); } System.out.println(max); // to end the line } ¡

31 ¡

slide-32
SLIDE 32

Fencepost ¡ques3on ¡

  • Modify ¡your ¡method ¡printNumbers ¡into ¡a ¡

new ¡method ¡printOdd ¡that ¡prints ¡all ¡prime ¡ numbers ¡up ¡to ¡a ¡max. ¡

– Example: ¡printOdd() for max = 20, prints ¡

1, 3, 5, 7, 9, 11, 13, 15, 17, 19

– If ¡the ¡maximum ¡is ¡less ¡than ¡1, ¡print ¡no ¡output.

32 ¡

slide-33
SLIDE 33

Fencepost ¡answer ¡

// Prints all odd numbers up to the given max. public static void printOdd() { int max = 20; if (max >= 1) { System.out.print(”1"); for (int i = 3; i <= max; i += 2) { System.out.print(", " + i); } System.out.println(); } }

33 ¡

slide-34
SLIDE 34

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 ¡

  • ne ¡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-­‑34 ¡

slide-35
SLIDE 35

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-­‑35 ¡

slide-36
SLIDE 36

String ¡class ¡documenta3on ¡

  • For ¡the ¡debugging ¡examples, ¡refer ¡to ¡the ¡

String ¡class ¡documenta3on ¡page: ¡ ¡

hep://docs.oracle.com/javase/6/docs/api/java/lang/String.html ¡ ¡

36 ¡

slide-37
SLIDE 37

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-­‑37 ¡

slide-38
SLIDE 38

General ¡Debugging ¡Techniques ¡(2) ¡

  • Comment ¡out ¡blocks ¡of ¡code ¡to ¡narrow ¡down ¡the ¡
  • ffending ¡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-­‑38 ¡

slide-39
SLIDE 39

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-­‑39 ¡

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'));

slide-40
SLIDE 40

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-­‑40 ¡

Result: Syntax error: c = s.substring(0,1); : incompatible types

found: java.lang.String required: char

slide-41
SLIDE 41

Debugging ¡Example ¡(3 ¡of ¡9) ¡

  • First ¡problem: ¡ ¡substring ¡returns ¡a ¡String, ¡use ¡

charAt ¡to ¡get ¡the ¡first ¡character: ¡

3-­‑41 ¡

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:

slide-42
SLIDE 42

Debugging ¡Example ¡(4 ¡of ¡9) ¡

3-­‑42 ¡

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.

slide-43
SLIDE 43

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-­‑43 ¡

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?

slide-44
SLIDE 44

Debugging ¡Example ¡(6 ¡of ¡9) ¡

  • Could ¡try ¡the ¡following ¡“patch” ¡

3-­‑44 ¡

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:

slide-45
SLIDE 45

Debugging ¡Example ¡(7 ¡of ¡9) ¡

3-­‑45 ¡

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.

slide-46
SLIDE 46

Debugging ¡Example ¡(8 ¡of ¡9) ¡

  • Fix: ¡ ¡We ¡use ¡&& ¡instead ¡of ¡|| ¡

3-­‑46 ¡

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'));

slide-47
SLIDE 47

Debugging ¡Example ¡(9 ¡of ¡9) ¡

  • Even ¡beeer: ¡ ¡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-­‑47 ¡

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);

slide-48
SLIDE 48

Preven3ve ¡Coding ¡

  • Incremental ¡Development ¡

– Write ¡a ¡liele ¡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 ¡

  • ther ¡watches, ¡and ¡periodically ¡switch ¡roles ¡

3-­‑48 ¡

slide-49
SLIDE 49

Before ¡geung ¡into ¡classes, ¡let ¡us ¡ discuss ¡more ¡on ¡methods ¡

49 ¡

slide-50
SLIDE 50

Structure ¡of ¡a ¡Java ¡program ¡

class: a program statement: a command to be executed method: a named group

  • f statements

50 ¡

slide-51
SLIDE 51

Review ¡our ¡understanding ¡of ¡ methods ¡

slide-52
SLIDE 52

Algorithms ¡

  • algorithm: ¡A ¡list ¡of ¡steps ¡for ¡solving ¡a ¡problem. ¡
  • Example ¡algorithm: ¡"Bake ¡sugar ¡cookies" ¡

– Mix ¡the ¡dry ¡ingredients. ¡ – Cream ¡the ¡bueer ¡and ¡sugar. ¡ – Beat ¡in ¡the ¡eggs. ¡ – S3r ¡in ¡the ¡dry ¡ingredients. ¡ – Set ¡the ¡oven ¡temperature. ¡ – Set ¡the ¡3mer. ¡ – Place ¡the ¡cookies ¡into ¡the ¡oven. ¡ – Allow ¡the ¡cookies ¡to ¡bake. ¡ – Spread ¡fros3ng ¡and ¡sprinkles ¡onto ¡the ¡cookies. ¡ – ... ¡

52 ¡

slide-53
SLIDE 53

Problems ¡with ¡previous ¡algorithm ¡

  • lack ¡of ¡structure: ¡Many ¡3ny ¡steps; ¡tough ¡to ¡remember. ¡
  • redundancy: ¡Consider ¡making ¡a ¡double ¡batch... ¡

– Mix ¡the ¡dry ¡ingredients. ¡ – Cream ¡the ¡bueer ¡and ¡sugar. ¡ – Beat ¡in ¡the ¡eggs. ¡ – S3r ¡in ¡the ¡dry ¡ingredients. ¡ – Set ¡the ¡oven ¡temperature. ¡ – Set ¡the ¡3mer. ¡ – Place ¡the ¡first ¡batch ¡of ¡cookies ¡into ¡the ¡oven. ¡ – Allow ¡the ¡cookies ¡to ¡bake. ¡ – Set ¡the ¡3mer. ¡ – Place ¡the ¡second ¡batch ¡of ¡cookies ¡into ¡the ¡oven. ¡ – Allow ¡the ¡cookies ¡to ¡bake. ¡ – Mix ¡ingredients ¡for ¡fros3ng. ¡ – ... ¡

53 ¡

slide-54
SLIDE 54

Structured ¡algorithms ¡

  • structured ¡algorithm: ¡Split ¡into ¡coherent ¡tasks. ¡

1 ¡Make ¡the ¡cookie ¡baeer. ¡ – Mix ¡the ¡dry ¡ingredients. ¡ – Cream ¡the ¡bueer ¡and ¡sugar. ¡ – Beat ¡in ¡the ¡eggs. ¡ – S3r ¡in ¡the ¡dry ¡ingredients. ¡ 2 ¡Bake ¡the ¡cookies. ¡ – Set ¡the ¡oven ¡temperature. ¡ – Set ¡the ¡3mer. ¡ – Place ¡the ¡cookies ¡into ¡the ¡oven. ¡ – Allow ¡the ¡cookies ¡to ¡bake. ¡ 3 ¡Add ¡fros3ng ¡and ¡sprinkles. ¡ – Mix ¡the ¡ingredients ¡for ¡the ¡fros3ng. ¡ – Spread ¡fros3ng ¡and ¡sprinkles ¡onto ¡the ¡cookies. ¡ ... ¡

54 ¡

slide-55
SLIDE 55

Removing ¡redundancy ¡

  • A ¡well-­‑structured ¡algorithm ¡can ¡describe ¡repeated ¡tasks ¡with ¡

less ¡redundancy. ¡

1 ¡Make ¡the ¡cookie ¡baeer. ¡ – Mix ¡the ¡dry ¡ingredients. ¡ – ... ¡ 2a ¡Bake ¡the ¡cookies ¡(first ¡batch). ¡ – Set ¡the ¡oven ¡temperature. ¡ – Set ¡the ¡3mer. ¡ – ... ¡ 2b ¡Bake ¡the ¡cookies ¡(second ¡batch). ¡ 3 ¡Decorate ¡the ¡cookies. ¡ – ... ¡

55 ¡

slide-56
SLIDE 56

A ¡program ¡with ¡redundancy ¡

public class BakeCookies { public static void main(String[] args) { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); } }

56 ¡

slide-57
SLIDE 57

Sta3c ¡methods ¡

  • sta:c ¡method: ¡A ¡named ¡group ¡of ¡statements. ¡
  • denotes ¡the ¡structure ¡of ¡a ¡program ¡
  • eliminates ¡redundancy ¡by ¡code ¡reuse ¡

– procedural ¡decomposi:on: ¡ dividing ¡a ¡problem ¡into ¡methods ¡

  • Wri3ng ¡a ¡sta3c ¡method ¡is ¡like ¡

adding ¡a ¡new ¡command ¡to ¡Java. ¡

class method A

 statement  statement  statement

method B

 statement  statement

method C

 statement  statement  statement

57 ¡

slide-58
SLIDE 58

Using ¡sta3c ¡methods ¡

  • 1. ¡Design ¡the ¡algorithm. ¡

– Look ¡at ¡the ¡structure, ¡and ¡which ¡commands ¡are ¡repeated. ¡ – Decide ¡what ¡are ¡the ¡important ¡overall ¡tasks. ¡

  • 2. ¡Declare ¡(write ¡down) ¡the ¡methods. ¡

– Arrange ¡statements ¡into ¡groups ¡and ¡give ¡each ¡group ¡a ¡

  • name. ¡
  • 3. ¡Call ¡(run) ¡the ¡methods. ¡

– The ¡program's ¡main ¡method ¡executes ¡the ¡other ¡methods ¡ to ¡perform ¡the ¡overall ¡task. ¡

58 ¡

slide-59
SLIDE 59

Gives ¡your ¡method ¡a ¡name ¡so ¡it ¡can ¡be ¡executed ¡

  • Syntax: ¡

public static void name() { statement; statement; ... statement; }

  • Example: ¡

public static void printWarning() {

System.out.println("This product causes cancer"); System.out.println("in lab rats and humans.");

}

Declaring ¡a ¡method ¡

59 ¡

slide-60
SLIDE 60

Calling ¡a ¡method ¡

Executes ¡the ¡method's ¡code ¡

  • Syntax: ¡

¡name(); ¡ – You ¡can ¡call ¡the ¡same ¡method ¡many ¡3mes ¡if ¡you ¡like. ¡

  • Example:

printWarning(); ¡ – Output: ¡ This product causes cancer in lab rats and humans.

60 ¡

slide-61
SLIDE 61

Program ¡with ¡sta3c ¡method ¡

public class FreshPrince { public static void main(String[] args) { rap(); // Calling (running) the rap method System.out.println(); rap(); // Calling the rap method again } // This method prints the lyrics to my favorite song. public static void rap() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside- down"); } }

Output: ¡

Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down

61 ¡

slide-62
SLIDE 62

When ¡to ¡use ¡methods ¡

  • Place ¡statements ¡into ¡a ¡sta3c ¡method ¡if: ¡

– The ¡statements ¡are ¡related ¡structurally, ¡and/or ¡ – The ¡statements ¡are ¡repeated. ¡

  • You ¡should ¡not ¡create ¡sta3c ¡methods ¡for: ¡

– An ¡individual ¡println ¡statement. ¡ – Only ¡blank ¡lines. ¡(Put ¡blank ¡printlns ¡in ¡main.) ¡ – Unrelated ¡or ¡weakly ¡related ¡statements. ¡ (Consider ¡spliung ¡them ¡into ¡two ¡smaller ¡methods.) ¡

62 ¡

slide-63
SLIDE 63

Final ¡cookie ¡program ¡

// This program displays a delicious recipe for baking cookies. public class BakeCookies3 { public static void main(String[] args) { makeBatter(); bake(); // 1st batch bake(); // 2nd batch decorate(); } // Step 1: Make the cake batter. public static void makeBatter() { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); } // Step 2: Bake a batch of cookies. public static void bake() { System.out.println("Set the oven temperature."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the

  • ven.");

System.out.println("Allow the cookies to bake."); } // Step 3: Decorate the cookies. public static void decorate() { System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); } }

63 ¡

slide-64
SLIDE 64

Methods ¡calling ¡methods ¡

public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } }

  • Output: ¡

This is message1. This is message2. This is message1. Done with message2. Done with main. ¡

64 ¡

slide-65
SLIDE 65
  • When ¡a ¡method ¡is ¡called, ¡the ¡program's ¡execu3on... ¡

– "jumps" ¡into ¡that ¡method, ¡execu3ng ¡its ¡statements, ¡then ¡ – "jumps" ¡back ¡to ¡the ¡point ¡where ¡the ¡method ¡was ¡called. ¡

public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } ... } ¡

public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } public static void message1() { System.out.println("This is message1."); }

Control ¡flow ¡

65 ¡

slide-66
SLIDE 66

Elimina3ng ¡further ¡redundancy ¡ using ¡parameterized ¡methods ¡

66 ¡

slide-67
SLIDE 67

Redundant ¡recipes ¡

  • Recipe ¡for ¡baking ¡20 ¡cookies: ¡

– Mix ¡the ¡following ¡ingredients ¡in ¡a ¡bowl: ¡

  • 4 ¡cups ¡flour ¡
  • 1 ¡cup ¡bueer ¡
  • 1 ¡cup ¡sugar ¡
  • 2 ¡eggs ¡
  • 40 ¡pounds ¡chocolate ¡chips ¡... ¡

– Place ¡on ¡sheet ¡and ¡Bake ¡for ¡about ¡10 ¡minutes. ¡

  • Recipe ¡for ¡baking ¡40 ¡cookies: ¡

– Mix ¡the ¡following ¡ingredients ¡in ¡a ¡bowl: ¡

  • 8 ¡cups ¡flour ¡
  • 2 ¡cups ¡bueer ¡
  • 2 ¡cups ¡sugar ¡
  • 4 ¡eggs ¡
  • 80 ¡pounds ¡chocolate ¡chips ¡... ¡

– Place ¡on ¡sheet ¡and ¡Bake ¡for ¡about ¡10 ¡minutes. ¡

67 ¡

slide-68
SLIDE 68

Parameterized ¡recipe ¡

  • Recipe ¡for ¡baking ¡20 ¡cookies: ¡

– Mix ¡the ¡following ¡ingredients ¡in ¡a ¡bowl: ¡

  • 4 ¡cups ¡flour ¡
  • 1 ¡cup ¡sugar ¡
  • 2 ¡eggs ¡
  • … ¡
  • Recipe ¡for ¡baking ¡N ¡cookies: ¡

– Mix ¡the ¡following ¡ingredients ¡in ¡a ¡bowl: ¡

  • N/5 ¡ ¡ ¡cups ¡flour ¡
  • N/20 ¡cups ¡bueer ¡
  • N/20 ¡cups ¡sugar ¡
  • N/10 ¡eggs ¡
  • 2N ¡bags ¡chocolate ¡chips ¡... ¡

– Place ¡on ¡sheet ¡and ¡Bake ¡for ¡about ¡10 ¡minutes. ¡

  • parameter: ¡A ¡value ¡that ¡dis3nguishes ¡similar ¡tasks. ¡

68 ¡

slide-69
SLIDE 69

Redundant ¡figures ¡

  • Consider ¡the ¡task ¡of ¡prin3ng ¡the ¡following ¡lines/boxes: ¡

************* ******* *********************************** ********** * * ********** ***** * * * * *****

69 ¡

slide-70
SLIDE 70

A ¡redundant ¡solu3on ¡

public class Stars1 { public static void main(String[] args) { lineOf13(); lineOf7(); lineOf35(); box10x3(); box5x4(); } public static void lineOf13() { for (int i = 1; i <= 13; i++) { System.out.print("*"); } System.out.println(); } public static void lineOf7() { for (int i = 1; i <= 7; i++) { System.out.print("*"); } System.out.println(); } public static void lineOf35() { for (int i = 1; i <= 35; i++) { System.out.print("*"); } System.out.println(); } ...

  • This code is redundant.
  • Would variables help?

Would constants help?

  • What is a better solution?

– line - A method to draw a line of any number of stars. – box - A method to draw a box of any size.

70 ¡

slide-71
SLIDE 71

Parameteriza3on ¡

  • parameter: ¡A ¡value ¡passed ¡to ¡a ¡method ¡by ¡its ¡caller. ¡

– Instead ¡of ¡lineOf7, ¡lineOf13, ¡write ¡line ¡to ¡draw ¡any ¡

  • length. ¡
  • When ¡declaring ¡the ¡method, ¡we ¡will ¡state ¡that ¡it ¡requires ¡a ¡

parameter ¡for ¡the ¡number ¡of ¡stars. ¡

  • When ¡calling ¡the ¡method, ¡we ¡will ¡specify ¡how ¡many ¡stars ¡to ¡draw. ¡

main line ******* 7 line ************* 13

71 ¡

slide-72
SLIDE 72

Declaring ¡a ¡parameter ¡

Sta-ng ¡that ¡a ¡method ¡requires ¡a ¡parameter ¡in ¡order ¡to ¡run ¡

public static void name ¡( ¡type name ¡) { statement(s); }

  • Example: ¡

public static void sayPassword(int code) { System.out.println("The password is: " + code); } – When ¡sayPassword ¡is ¡called, ¡the ¡caller ¡must ¡specify ¡ the ¡integer ¡code ¡to ¡print. ¡

72 ¡

slide-73
SLIDE 73

Passing ¡a ¡parameter ¡

Calling ¡a ¡method ¡and ¡specifying ¡values ¡for ¡its ¡parameters ¡

name ¡(expression);

  • Example: ¡

public static void main(String[] args) { sayPassword(42); sayPassword(12345); } Output: ¡ The password is 42 The password is 12345

73 ¡

slide-74
SLIDE 74

Parameters ¡and ¡loops ¡

  • A ¡parameter ¡can ¡guide ¡the ¡number ¡of ¡repe33ons ¡of ¡a ¡loop. ¡

public static void main(String[] args) { chant(3); } public static void chant(int times) { for (int i = 1; i <= times; i++) { System.out.println("Just a salad..."); } } ¡ Output: ¡ Just a salad... Just a salad... Just a salad...

74 ¡

slide-75
SLIDE 75

How ¡parameters ¡are ¡passed ¡

  • When ¡the ¡method ¡is ¡called: ¡

– The ¡value ¡is ¡stored ¡into ¡the ¡parameter ¡variable. ¡ – The ¡method's ¡code ¡executes ¡using ¡that ¡value. ¡

public static void main(String[] args) { chant(3); chant(7); } public static void chant(int times) { for (int i = 1; i <= times; i++) { System.out.println("Just a salad..."); } }

3 7

75 ¡

slide-76
SLIDE 76

Common ¡errors ¡

  • If ¡a ¡method ¡accepts ¡a ¡parameter, ¡it ¡is ¡illegal ¡to ¡call ¡it ¡without ¡

passing ¡any ¡value ¡for ¡that ¡parameter. ¡

chant(); // ERROR: parameter value required

  • The ¡value ¡passed ¡to ¡a ¡method ¡must ¡be ¡of ¡the ¡correct ¡type. ¡

chant(3.7); // ERROR: must be of type int

  • Exercise: ¡Change ¡the ¡Stars ¡program ¡to ¡use ¡a ¡parameterized ¡

method ¡for ¡drawing ¡lines ¡of ¡stars.

76 ¡

slide-77
SLIDE 77

Stars ¡solu3on ¡

// Prints several lines of stars. // Uses a parameterized method to remove redundancy. public class Stars2 { public static void main(String[] args) { line(13); line(7); line(35); } // Prints the given number of stars plus a line break. public static void line(int count) { for (int i = 1; i <= count; i++) { System.out.print("*"); } System.out.println(); } }

77 ¡

slide-78
SLIDE 78

Acknowledgments ¡

  • A ¡subset ¡of ¡the ¡previous ¡slides ¡have ¡been ¡

either ¡directly ¡taken ¡from ¡or ¡derived ¡from ¡ supplements ¡for ¡the ¡book: ¡

Building ¡Java ¡Programs: ¡A ¡Back ¡to ¡Basics ¡Approach, ¡ 2nd ¡edi:on ¡ by ¡Stuart ¡Reges ¡and ¡Marty ¡Stepp ¡

hep://www.buildingjavaprograms.com/supplements.shtml ¡ ¡

78 ¡