380 likes | 397 Views
Control Structures. (and user input). 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
E N D
Control Structures (and user input)
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
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
boolean expression true false statement Logic of an if statement
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 ==
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."); } }
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
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
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
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
boolean expression true false statement1 statement2 Logic of an if-else statement
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"); } }
More Boolean Expressions • boolean operators: • ! (not) • &, && (and) • |, || (or) • These operators take boolean operands and return boolean values • Methods can also return boolean values
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
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
Logical AND and Logical OR • The truth table shows all possible true-false combinations of the terms
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
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
Complex Expressions • Specific expressions can be evaluated using truth tables
More Conditionals • The conditional operator condition ? expression1 : expression2 • The switch statement • Useful for enumerating a series of conditions • Covered in text
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
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
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
boolean expression true false statement Logic of a while Loop
Example class 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
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
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
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
statement true boolean expression false Logic of a do Loop
Example class DoWhileExample { public static void main(String[] args) { int count = 0; do { System.out.print(count); System.out.print(" "); count++; } while ( count < 5 ); } }
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
initialization boolean expression true false statement increment Logic of a for loop
Example class ForExample { public static void main(String[] args) { int count; for ( count=0; count<5; count++ ) { System.out.print(count); System.out.print(" "); } } }
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
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
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
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();
Scanner Example import 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