1 Control Structures (and user input)
1
Control Structures
(and user input)
2
Flow of Control
The order statements are executed is called flow of control
By default, statements in a method are executed consecutively
Control structures let us control the flow of control Decide if certain statements should be executed Repeat the execution of certain statements
3
The if Statement
Syntax<cond statement> ::= if (<boolean expr>) <statement>
<cond statement> ::= if (<boolean expr>) <statement>
else <statement>
Curly braces can be used to make it a compound statement
<statement> ::= {<statement>; <statement>;…}
This applies wherever a statement can occur
4
Logic of an if statement
booleanexpression
statement
truefalse
5
Boolean Expressions
Evaluate to true or false Relational operators:
> (greater than) < (less than) >= (greater than or equal to) <= (less than or equal to) == (equal to) != (not equal to)
Be careful distinguishing = and ==
6
An if Example
class IfExample {
public static void main(String[] args) {
int value = 6;
if ( value == 6 )System.out.println("equal");
System.out.println(“Always printed.");}
}
7
Indentation
Indent the if statement to indicate that relationship
Consistent indentation style makes a program easier to read and understand
"Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live."
-- Martin Golding
8
Braces or No Braces?
These are both valid:if(value==6)
{
System.out.println(“equal”);
}
if(value==6)
System.out.println(“equal”);
Rule of thumb: only omit braces when it is obvious where the conditional starts/ends
9
What do these statements do? if (top >= MAXIMUM)
top = 0;Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM
if (total != stock + warehouse) inventoryError = true;
Sets a flag to true if the value of total is not equal to the sum of stock and warehouse
if (total > MAX) System.out.println ("Error!!"); errorCount++;
Confusing indentation!! errorCount gets incremented, no matter what the value of total is
10
The if-else Statement
An else clause is added to give an alternative statement to execute
There isn’t really an “else if” in Java … you can fake it, however… The statement following else can be another if
statement … we’ll see an example in a minute
11
Logic of an if-else statement
booleanexpression
statement1
true false
statement2
12
An else-if Example
class ConditionalExample {
public static void main(String[] args) {
int value = 6;
if ( value == 6 )System.out.println("equal");
else if ( value < 6 ) System.out.println("less");
else System.out.println("more");
}}
13
More Boolean Expressions
boolean operators: ! (not) &, && (and) |, || (or)
These operators take boolean operands and return boolean values
Methods can also return boolean values
14
Logical NOT
Also called logical negation
If some boolean condition a is true, then !a is false; if a is false, then !a is true
Logical expressions can be shown using a truth table
a !a
true false
false true
15
Logical AND and Logical OR
a && b is true if both a and b are true, and false otherwise
a || b is true if a or b or both are true, and false otherwise
16
Logical AND and Logical OR The truth table shows all possible true-false
combinations of the terms
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
17
Lazy Operators
&& and || are “lazy” They only evaluate the right side if they have to
& and | are “active” They always evaluate both operands
This differs from related programming languages
18
Complex Expressions
Several operators in one statement:
if (total < MAX+5 && !found) System.out.println ("Processing…");
All logical operators have lower precedence than the relational operators
Logical NOT has higher precedence than logical AND and logical OR
19
Complex Expressions
Specific expressions can be evaluated using truth tables
total < MAX found !found total < MAX && !found
false false true false
false true false false
true false true true
true true false false
20
More Conditionals
The conditional operatorcondition ? expression1 : expression2
The switch statement Useful for enumerating a series of conditions
Covered in text
21
Thoughts on Comparing Values Be careful using == with floating point values
defining a threshold sometimes better Be extra special super careful using == with
Strings you are comparing references, not strings use the equals method if that’s what you want
Same for other object types in the future, we’ll be defining equals methods
22
Repition Statements
Also called loops Let certain statements be executed multiple
times Controlled by boolean expresssions Java has 3 kinds of loops:
while do for
23
The While Statement
Syntax:<while statement> ::= while (<boolean expr>) <statement>
If the expression is true, then the statement is executed
After executing the statement, we check the expression again and repeat
The statement will run 0 or more times
24
Logic of a while Loop
statement
true false
booleanexpression
25
Exampleclass WhileExample {
public static void main(String[] args) {
int count = 0;
while ( count < 5 ) {
System.out.print(count);System.out.print(" ");count++;
}}
}
Output: 0 1 2 3 4
26
Infinite Loops
The body of a while loop must eventually make the boolean expression false …otherwise it is an infinite loop
Always check to make sure your loops will terminate
An infinite loops continues until interrupted (CTRL-C) or a memory error occurs
27
Nested Loops
How many times will the string "Here" be printed?
count1 = 1;while (count1 <= 10){ count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++;} 10 * 20 = 200
28
The do…while Statement
syntax:<do while statement> ::= do <statement>
while (<boolean expr>)
Run the condition, then check the boolean expression and repeat The statement will run 1 or more times
29
Logic of a do Loop
true
booleanexpression
statement
false
30
Example
class DoWhileExample {
public static void main(String[] args) {
int count = 0;
do {
System.out.print(count);System.out.print(" ");count++;
} while ( count < 5 );}
}
31
The for Loop
syntax:<for statement> ::= for (<statement>; <boolean expr>;
<statement>) <statement>
Three things in the parentheses: The initialization statement The continuation condition The increment (or step) statement
32
Logic of a for loop
statement
true
booleanexpression
false
increment
initialization
33
Example
class ForExample {
public static void main(String[] args) {
int count;
for ( count=0; count<5; count++ ) {
System.out.print(count);System.out.print(" ");
}}
}
34
Equivalent while Structure
A for loop is functionally equivalent to:initialization;
while(condition)
{
statement;
increment;
}
In general, all the loop statements are equivalent… use the “easiest” loop for each application
35
More on the for Loop
Often used when a loop is to be executed a fixed number of times known in advance
Formally, all the parenthetic information is optional
There is also an Iterator version… this will make more sense when we know what Iterators are
36
User Input
Traditionally this was messy in Java New in Java 5.0 – the Scanner class
Create a Scanner object with input from the console
Use Scanner methods to retrieve input of appropriate type
Keyboard input is represented by the System.in object
37
Creating a Scanner
The following line creates a Scanner object that reads from the keyboard:
Scanner scan = new Scanner (System.in);
The new operator creates the Scanner object
Once created, the Scanner object can be used to invoke various input methods, such as:
answer = scan.nextLine();
38
Scanner Exampleimport java.util.Scanner; // for Java 5.0+
class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);int i = sc.nextInt();double d = sc.nextDouble();
System.out.print("First value: ");System.out.println(i);System.out.print("Second value: ");System.out.println(d);
}}
Historical Interlude