53
5. Conditionals 5. Conditionals & Loops & Loops Based on Based on Java Software Development, 5 Java Software Development, 5 th th Ed. Ed. By Lewis &Loftus By Lewis &Loftus

5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Embed Size (px)

Citation preview

Page 1: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

5. Conditionals & 5. Conditionals & LoopsLoops

Based on Based on Java Software Development, 5Java Software Development, 5thth Ed. Ed.

By Lewis &LoftusBy Lewis &Loftus

Page 2: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopics

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Page 3: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Program Control Program Control StructuresStructures

The program executes each The program executes each statement one after another, unless statement one after another, unless otherwise directed explicitly. otherwise directed explicitly.

Order of execution statement is Order of execution statement is called “flow of control.”called “flow of control.”

A program needs only three control A program needs only three control structures:structures: Sequence (default)Sequence (default) Conditional (decision) Conditional (decision) Iteration (loop)Iteration (loop)

Page 4: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Conditional StatementsConditional Statements

Conditional statement lets you Conditional statement lets you choose which statement to execute choose which statement to execute next, depending of a boolean next, depending of a boolean condition.condition.

Conditional StatementsConditional Statements ifif statement statement if-elseif-else statement statement switchswitch statement statement

Page 5: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

If StatementIf Statement

if (boolCondition)if (boolCondition) someStatement; someStatement;

if (boolCondition)if (boolCondition){{ someStatement1; someStatement1; someStatement2; someStatement2;}}

boolCondition

someStatement

truefalse

Page 6: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

If StatementIf Statement

final int VOTE_AGE = 18;int age;

Scanner scan = new Scanner(System.in);System.out.println(“How old are you?”);age = scan.nextInt();

If (age >= VOTE_AGE){ System.out.println(“Since you are over “ + VOTE_AGE + “,\nyou can vote.”);}

Page 7: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Relational OperationsRelational Operations A condition often uses one of Java's equality A condition often uses one of Java's equality

operators or relational operators, which all operators or relational operators, which all return boolean resultsreturn boolean results::

== equal toequal to != not equal tonot equal to < less thanless than > greater thangreater than <= less than or equal toless than or equal to >= greater than or equal togreater than or equal to

Note the difference between the equality Note the difference between the equality operator (==) and the assignment operator operator (==) and the assignment operator (=)(=)

Page 8: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Logical OperatorsLogical Operators

If (5 > 3 && 8 <= 8)If (5 > 3 && 8 <= 8) System.out.println(“Hi.”); System.out.println(“Hi.”);

Is (5 > 3 && 8 <= 8) true, or false?Is (5 > 3 && 8 <= 8) true, or false? Logical operators take boolean Logical operators take boolean

expressionsexpressions ! Logical NOT! Logical NOT && Logical AND&& Logical AND || Logical OR|| Logical OR

Page 9: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Logical OperatorsLogical Operators

int num;

Scanner scan = new Scanner(System.in);System.out.println(“Enter a 2-digit number“);num = scan.nextInt();

if ((num >= 10) && (num < 100)){ System.out.println(“Thnak you.”);

}

Page 10: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Your TurnYour Turn

Given:Given:int a = 1;int a = 1;int b = 2;int b = 2;int c = 3;int c = 3;int d = 4;int d = 4;

True or False?True or False?1.1. a < b && c > da < b && c > d

2.2. a < b || c > da < b || c > d

3.3. a < b && d > a + ba < b && d > a + b

4.4. !(c < d)!(c < d)

Page 11: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Truth TableTruth Table

AA BB !A!A A && BA && B A || BA || B

TT TT FF TT TT

TT FF FF FF TT

FF TT TT FF TT

FF FF TT FF FF

Page 12: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Boolean ExpressionsBoolean Expressions

a > ba > b foundfound !found!found a > b && !founda > b && !found

TT TT ?? ??

TT FF ?? ??

FF TT ?? ??

FF FF ?? ??

Page 13: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Short-circuited OperatorShort-circuited Operator

If ((a > b) && (c < d))If ((a > b) && (c < d)) If (a > b) is If (a > b) is falsefalse, then the whole , then the whole

espression is espression is falsefalse. Thus, Java does not . Thus, Java does not evaluate (c < d).evaluate (c < d).

If ((a > b) || (c < d))If ((a > b) || (c < d)) If (a > b) is If (a > b) is truetrue, then the whole , then the whole

expressions is expressions is truetrue. Thus, Java does not . Thus, Java does not evaluate (c < d).evaluate (c < d).

Page 14: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopics

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Page 15: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

If-Else StatementIf-Else Statement if (boolCondition)if (boolCondition) someStatement; someStatement;elseelse anotherStatement; anotherStatement;

if (boolCondition)if (boolCondition){{ someStatement1; someStatement1; someStatement2; someStatement2;}}elseelse{{ anotherStatement1; anotherStatement1; anotherStatement2; anotherStatement2;}}

conditionevaluated

statement1

true false

statement2

Page 16: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

if –else Statementsif –else Statementsif (number > 0) System.out.println(number + " is positive.”); else System.out.println(number + " is non-pos.”);

if (score >= 70) { grade = "Pass"; System.out.println("You passed the test."); } else { grade = "Fail"; System.out.println("You did not pass “ + “the test.”); }

Page 17: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Example ProgramExample Program

CoinFlip.javaCoinFlip.java Coin.javaCoin.java

Page 18: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Unmatched ElseUnmatched Else

What is the output from the following What is the output from the following example? example?

x = 5; if (x < 4) if (x > 0) System.out.print("Hi"); else System.out.print("Ho");

Page 19: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

AnswerAnswer

Output: Output: nonenone An An elseelse is matched with the nearest is matched with the nearest

ifif.. Same as:Same as:

x = 5; if (x < 4) if (x > 0) System.out.print("Hi"); else System.out.print("Ho");

Page 20: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Q & AQ & A QQ: How do you associate a nested else : How do you associate a nested else

with a particular if?with a particular if? AA::

x = 5; if (x < 4){ if (x > 0) System.out.print("Hi");} else { System.out.print("Ho");}

Page 21: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Nested Nested if if StatementStatementchar grade;

int score;

if (score >= 90) grade = ‘A’;else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;

Page 22: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Nested IfNested If

>= 90

score input

>= 80

>= 70

>= 60

grade = ‘A

Grade = ‘F’

grade = ‘B’

grade = ‘C’

Grade = ‘D’

T TF

F

F

F

T

T

T

Page 23: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Equivalent Equivalent if-else-ifif-else-if

char grade;

int score;

if (score >= 90) grade = ‘A’;else if (score >= 80) grade = ‘B’;else if (score >= 70) grade = ‘C’;else if (score >= 60) grade = ‘D’;else grade = ‘F’;

Page 24: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

If-else-ifIf-else-if

>= 90

score input

>= 80

>= 70

>= 60

grade = ‘A

Grade = ‘F’

grade = ‘B’

grade = ‘C’

Grade = ‘D’

T T

F

F

F

T

T

T

F

Page 25: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

ExercisesExercises

Write a code segment which converts Write a code segment which converts a letter grade into an equivalent a letter grade into an equivalent numeric grade. I.e., A numeric grade. I.e., A 4, B 4, B 3, C 3, C 2, D 2, D 1, F 1, F 0. 0.

Page 26: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

switchswitch Statement Statement

Use Use switchswitch statement when: statement when: Test Test condition condition involves matching with involves matching with

severalseveral cases cases Each value matched is an integer valueEach value matched is an integer value

—i.e., byte, short, int, or char (not —i.e., byte, short, int, or char (not String)String)

Note that the Note that the switchswitch statement cannot statement cannot be used to convert a range of numeric be used to convert a range of numeric scores to letter grades, e.g., 90-100 scores to letter grades, e.g., 90-100 A, A, 80-89 80-89 B, etc. Why? B, etc. Why?

Page 27: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

switchswitch Statement: Statement: ExampleExample

char grade;

int score;

switch (grade){ case 'A': score = 4; break; case 'B': score = 3; break; case 'C': score = 2; break; case 'D': score = 1; break; default: score = 0; }

Page 28: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Your TurnYour Turn

Use a switch statement to count the Use a switch statement to count the number of vowels in a statement.number of vowels in a statement.

Page 29: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

SolutionSolution String state String state input input int a = 0; e = 0; I = 0; o = 0; u = 0int a = 0; e = 0; I = 0; o = 0; u = 0 for (int I = 0; I < state.lenght(); i++)for (int I = 0; I < state.lenght(); i++)

ch + state.chartAt(i) ch + state.chartAt(i) switch(ch)switch(ch)

case ‘a’: a++; break; case ‘a’: a++; break; case ‘e’: e++; break; case ‘e’: e++; break; case ‘I’: i++; break; case ‘I’: i++; break; case ‘o’; o++; break; case ‘o’; o++; break; case ‘u’; u++; case ‘u’; u++;

Page 30: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopics

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Page 31: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Comparing Comparing Floating Point NumbersFloating Point Numbers

Given:Given:int a, b;int a, b;float x, y;float x, y;

(a == b) is clear; but(a == b) is clear; but (x == y) should be avoided(x == y) should be avoided

The expression may never be true.The expression may never be true. Two floating point numbers are equal only if Two floating point numbers are equal only if

they have the exact representationthey have the exact representation E.g., 0.3000000 is represented as 0.2999999.E.g., 0.3000000 is represented as 0.2999999.

Page 32: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Comparing Comparing Floating Point Numbers Floating Point Numbers

(cont.)(cont.) Instead, use the following expression.Instead, use the following expression.

final float DELTA = 0.00001;final float DELTA = 0.00001;float x, y;float x, y;……if (abs(a – b) <= DELTA)if (abs(a – b) <= DELTA) System.out.println(“close System.out.println(“close enough.”);enough.”);

Page 33: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Comparing CharacteresComparing Characteres Comparison of charactersComparison of characters

Based on Unicode numbersBased on Unicode numbers Called Called lexicographiclexicographic order order

Note that numeric digit and alphabetic Note that numeric digit and alphabetic characters have consecutive Unicode numbers.characters have consecutive Unicode numbers.

CharactersCharacters Unicode ValuesUnicode Values

0 – 90 – 9 48 through 5748 through 57

A – ZA – Z 65 through 9065 through 90

a – za – z 97 through 12297 through 122

Page 34: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Comparing StringsComparing Strings

Given:Given:String s1, s2;String s1, s2;s1 = new String(“Abe”);s1 = new String(“Abe”);s2 = new String(“Abe”);s2 = new String(“Abe”);

(s1 == s2) will return false, because s1 (s1 == s2) will return false, because s1 and s2 are essentially memory addresses.and s2 are essentially memory addresses.

Generally speaking, do not use relational Generally speaking, do not use relational operators to compare objects.operators to compare objects.

Page 35: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Comparing Strings Comparing Strings (cont.)(cont.)

Instead, use String mentods:Instead, use String mentods: If(s1.equals(s2))If(s1.equals(s2)) System.out.println(“s1 == s2”); System.out.println(“s1 == s2”);

n = s1.compareWith(s2);n = s1.compareWith(s2);

If n is 0, then s1 == s2If n is 0, then s1 == s2

If n is -1, then s1 < s2If n is -1, then s1 < s2

If n = 1, then s1 > s2If n = 1, then s1 > s2

Page 36: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Comparing Strings Comparing Strings (cont.)(cont.)

The following expressions are all The following expressions are all true.true. ““BOOK” < “book”BOOK” < “book” ““Venice” < “rome”Venice” < “rome” ““America” < “acupuncture”America” < “acupuncture” ““Santa Clara” < “Santa barbara”Santa Clara” < “Santa barbara” ““class” < “classical”class” < “classical”

Page 37: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopics

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Page 38: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

While StatementWhile Statement

While (boolean condition)While (boolean condition){{ statement1 statement1 statement2 statement2 statement3 statement3}}

One of the statements in the One of the statements in the loop must cause a change in loop must cause a change in the value of the boolean the value of the boolean condition.condition.

statements

true false

conditionevaluated

Page 39: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

While Statement (cont.)While Statement (cont.) cnt = 1;cnt = 1;

while (cnt <=10)while (cnt <=10){ sum += cnt;{ sum += cnt; cnt++; cnt++;}}

While Statement Requirements:While Statement Requirements:1.1. Loop control variable (LCV) is initializedLoop control variable (LCV) is initialized2.2. LCV is checked in the condition LCV is checked in the condition

expressionexpression3.3. LCV is updated in the loopLCV is updated in the loop

Average.javaAverage.java WinPercentage.javaWinPercentage.java

Page 40: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

whilewhile Loop: Example Loop: Example

Suppose that you save money each Suppose that you save money each day, starting with 1 penny on day day, starting with 1 penny on day one, 2 pennies on day two, 4 pennies one, 2 pennies on day two, 4 pennies on day three, 8 pennies on day four, on day three, 8 pennies on day four, etc., each day doubling the amount etc., each day doubling the amount from the preceding day.  Write a from the preceding day.  Write a program that calculates the number program that calculates the number of days it takes to save at least of days it takes to save at least $1,000,000.  $1,000,000. 

Page 41: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

class WhileTest{ public static void main(String args[]){ int day; long total = 0; long save; long goal = 100000000; day = 0; save = 1;

while (total < goal){ day++; total = total + save; save = 2 * save; } System.out.println("It takes " + day + " days to save at least $1,000,000."); }}

Page 42: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Nested LoopsNested Loops How many times will the string "Here" be printed?How many times will the string "Here" be printed?

count1 = 1;while (count1 <= 5){ count2 = 1; while (count2 <= 3) { System.out.println ("Here"); count2++; } count1++;}

Page 43: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Sentinel ValueSentinel Value Read and print sum of numbers input. Read and print sum of numbers input.

Stop input when -1 is read.Stop input when -1 is read.

int sum = 0;int sum = 0;int num;int num;num = scan.nextInt();num = scan.nextInt();while (num != -1) {while (num != -1) { sum += num; sum += num; num = scan.nextInt(); num = scan.nextInt();}}System.out.println(“Sum: “ + sum);System.out.println(“Sum: “ + sum);

Page 44: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Sentinel Value (Cont.)Sentinel Value (Cont.) Read and print the average of numbers input. Read and print the average of numbers input.

Stop input when -1 is read.Stop input when -1 is read.

int sum = 0;int sum = 0;int count = 0;int count = 0;int num;int num;double ave;double ave;

num = scan.nextInt();num = scan.nextInt();while (num != -1) {while (num != -1) { count++; count++; sum += num; sum += num; num = scan.nextInt(); num = scan.nextInt();}}

System.out.println(“Ave: “ System.out.println(“Ave: “ + (double)sum / count); + (double)sum / count);

Page 45: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopics

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Page 46: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

For-LoopFor-Loop While-loopWhile-loop

sum = 0;sum = 0;cnt = 1;cnt = 1;while (cnt <= 10)while (cnt <= 10){ sum += cnt;{ sum += cnt; cnt++; cnt++;}}

For-loopFor-loop

sum = 0;sum = 0;for (int cnt = 1; cnt <= 0; cnt++)for (int cnt = 1; cnt <= 0; cnt++){{ sum += 0; sum += 0;}}

Page 47: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Example ProgramsExample Programs

Multiples.javaMultiples.java Stars.javaStars.java

Page 48: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

For-LoopFor-Loopint[] aList = {2, 4, 6, 8, 10};

for (int i = 0; i < aList.length; i++) System.out.println(aList[i] + “ ”);

int sum = 0;for (int i = 0; i < aList.length; i++) sum = sum + aList[i];

System.out.println(“Sum: “ + sum);

Page 49: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Triangle PatternsTriangle Patterns Q: Write a program to produce the Q: Write a program to produce the

following patterns (one after another).following patterns (one after another).

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

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

AnswerAnswer: :

Page 50: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

class ArrayTest { String[] names = {"Mike", "Mary", "Martha"}; String[] addresses = new String[names.length]; void printList(){ for (int i = 0; i < names.length; i++) System.out.println(names[i] + " lives at " + addresses[i]); }

public static void main(String args[]){ ArrayTest aList = new ArrayTest(); aList.addresses[0] = "123 Apple St."; aList.addresses[1] = "234 Banana Blvd."; aList.addresses[2] = "345 Citrus Ct."; aList.printList(); } }

Page 51: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Do-LoopDo-Loop dodo{{ statement1; statement1; statement2; statement2;} while (boolean condition)} while (boolean condition)

Boolean condition is checked at the bottom Boolean condition is checked at the bottom of the loop.of the loop.

A Do-Loop executes at least once, but A Do-Loop executes at least once, but While-Loop executes 0 or more times.While-Loop executes 0 or more times.

Page 52: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Comparing Do-Loop withComparing Do-Loop withWhile-LoopWhile-Loop

statement

true false

conditionevaluated

The while Loop

true

conditionevaluated

statement

false

The do Loop

Page 53: 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopics

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components