5. Conditionals & 5. Conditionals & LoopsLoops
Based on Based on Java Software Development, 5Java Software Development, 5thth Ed. Ed.
By Lewis &LoftusBy 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
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)
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
If StatementIf Statement
if (boolCondition)if (boolCondition) someStatement; someStatement;
if (boolCondition)if (boolCondition){{ someStatement1; someStatement1; someStatement2; someStatement2;}}
boolCondition
someStatement
truefalse
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.”);}
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 (=)(=)
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
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.”);
}
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)
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
Boolean ExpressionsBoolean Expressions
a > ba > b foundfound !found!found a > b && !founda > b && !found
TT TT ?? ??
TT FF ?? ??
FF TT ?? ??
FF FF ?? ??
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).
TopicsTopics
The if Statement and Conditions
Other Conditional Statements
Comparing Data
The while Statement
Iterators
Other Repetition Statements
Decisions and Graphics
More Components
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
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.”); }
Example ProgramExample Program
CoinFlip.javaCoinFlip.java Coin.javaCoin.java
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");
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");
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");}
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’;
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
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’;
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
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.
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?
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; }
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.
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++;
TopicsTopics
The if Statement and Conditions
Other Conditional Statements
Comparing Data
The while Statement
Iterators
Other Repetition Statements
Decisions and Graphics
More Components
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.
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.”);
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
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.
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
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”
TopicsTopics
The if Statement and Conditions
Other Conditional Statements
Comparing Data
The while Statement
Iterators
Other Repetition Statements
Decisions and Graphics
More Components
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
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
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.
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."); }}
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++;}
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);
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);
TopicsTopics
The if Statement and Conditions
Other Conditional Statements
Comparing Data
The while Statement
Iterators
Other Repetition Statements
Decisions and Graphics
More Components
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;}}
Example ProgramsExample Programs
Multiples.javaMultiples.java Stars.javaStars.java
For Loop (Your Turn)For Loop (Your Turn)
Write an algorithm to solve each Write an algorithm to solve each problemproblem
1.1. Read a year value and check if it is a Read a year value and check if it is a leap year. Do this for 10 inputsleap year. Do this for 10 inputs
2.2. In the preceding problem, let the user In the preceding problem, let the user determine how many times to repeatdetermine how many times to repeat
3.3. Let the user enter the first year and Let the user enter the first year and last year values, and count the number last year values, and count the number of leap years between the two years.of leap years between the two years.
Solution 1Solution 1
loop (for n = 1 to 10) loop (for n = 1 to 10) year year input input put year put year
if (year is a leap year) then if (year is a leap year) then put “ is a leap year” put “ is a leap year” else else put “ is NOT a leap year” put “ is NOT a leap year” end if end ifend loopend loop
Solution 2Solution 2
last last input input
loop (for n = 1 to last) loop (for n = 1 to last) year year input input put year put year
if (year is a leap year) then if (year is a leap year) then put “ is a leap year” put “ is a leap year” else else put “ is NOT a leap year” put “ is NOT a leap year” end if end ifend loopend loop
Solution 3Solution 3 count count 0 0
start start input inputlast last input input
loop (for year = start to last) loop (for year = start to last) if (year is a leap year) then if (year is a leap year) then count++ count++ end if end ifend loopend loop
put countput count
Triangle PatternsTriangle Patterns Q: Write an algorithm to produce each of Q: Write an algorithm to produce each of
the following patterns (one after another).the following patterns (one after another).
* ** *** **** ***** ****** ******* ******** ********* **********
* ** *** **** ***** ****** ******* ******** ********* **********
leftIncreaseleftIncrease rightIncreaserightIncrease
leftIncreaseleftIncreaseloop (for row = 1 to MAX) loop (for col = 1 to row) print ‘*’ end loop printend loop
leftIncreaserightIncreaseloop (for row = 1 to MAX) loop (for col = 1 to MAX – row) print ‘ ‘ end loop
loop (for col = 1 to row) print ‘*’ end loop printend loop
Triangle PatternsTriangle Patterns Q: Write an algorithm to produce each of Q: Write an algorithm to produce each of
the following patterns (one after another).the following patterns (one after another).
*************************** ******* ****** ***** **** *** ** *
********** ********* ******** ******* ****** ***** **** *** ** *
rightIncreaserightIncreaselefttDecreaselefttDecrease
leftIncreaseleftDecreaseloop (for row = MAX down to 1) loop (for col = 1 to MAX) print ‘*’ end loop printend loop
leftIncreaserightDecreaseloop (for row = 1 to MAX) loop (for col = 1 to row - 1) print ‘ ‘ end loop
loop (for col = 1 to MAX – row + 1) print ‘*’ end loop printend loop
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);
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(); } }
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.
Comparing Do-Loop withComparing Do-Loop withWhile-LoopWhile-Loop
statement
true false
conditionevaluated
The while Loop
true
conditionevaluated
statement
false
The do Loop
TopicsTopics
The if Statement and Conditions
Other Conditional Statements
Comparing Data
The while Statement
Iterators
Other Repetition Statements
Decisions and Graphics
More Components