Top Banner
1 Control Structures (and user input)
38

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.

Dec 19, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 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.

1

Control Structures

(and user input)

Page 2: 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.

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

Page 3: 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.

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

Page 4: 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.

4

Logic of an if statement

booleanexpression

statement

truefalse

Page 5: 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.

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 ==

Page 6: 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.

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.");}

}

Page 7: 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.

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

Page 8: 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.

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

Page 9: 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.

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

Page 10: 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.

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

Page 11: 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.

11

Logic of an if-else statement

booleanexpression

statement1

true false

statement2

Page 12: 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.

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

}}

Page 13: 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.

13

More Boolean Expressions

boolean operators: ! (not) &, && (and) |, || (or)

These operators take boolean operands and return boolean values

Methods can also return boolean values

Page 14: 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.

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

Page 15: 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.

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

Page 16: 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.

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

Page 17: 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.

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

Page 18: 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.

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

Page 19: 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.

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

Page 20: 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.

20

More Conditionals

The conditional operatorcondition ? expression1 : expression2

The switch statement Useful for enumerating a series of conditions

Covered in text

Page 21: 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.

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

Page 22: 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.

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

Page 23: 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.

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

Page 24: 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.

24

Logic of a while Loop

statement

true false

booleanexpression

Page 25: 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.

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

Page 26: 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.

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

Page 27: 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.

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

Page 28: 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.

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

Page 29: 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.

29

Logic of a do Loop

true

booleanexpression

statement

false

Page 30: 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.

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

}

Page 31: 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.

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

Page 32: 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.

32

Logic of a for loop

statement

true

booleanexpression

false

increment

initialization

Page 33: 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.

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

}}

}

Page 34: 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.

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

Page 35: 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.

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

Page 36: 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.

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

Page 37: 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.

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

Page 38: 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.

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