jaeki song isqs6337 java lecture 04 control structure - selection, and repetition -

36
ISQS6337 JAVA Jaeki Song Lecture 04 Control Structure - Selection, and Repetition -

Upload: giles-welch

Post on 31-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

ISQS6337 JAVA

Jaeki Song

Lecture 04Control Structure- Selection, and

Repetition -

ISQS6337 JAVA

Jaeki Song

Outline

• Selection– if statement– switch statement

• Repetition– while statement– for statement

ISQS6337 JAVA

Jaeki Song

Control Structure

• A standard progression of logical steps to control the sequence of statement execution

• Basic control structures– Sequence– Selection– Repetition

ISQS6337 JAVA

Jaeki Song

Flowcharts

• Often use either flowcharts or pseudocode to plan a program’s logic– Pseudocode

• Write down the steps required to accomplish a given task using English

– Flowcharts• Write the steps you need in diagram form, as a

series of shapes connected by arrows

ISQS6337 JAVA

Jaeki Song

Sequence Logical Control Structure

• This is the overriding control structure.

• Instructions are carried out in order or sequence.

• Action can be inputs, processes, or outputs

Action 1

Action 2

Action 3

ISQS6337 JAVA

Jaeki Song

Selection Logical Control Structure I

• Instructions are executed depending on the outcome of a test; also called branching– If….then….else

Condition

Action 1 Action 2

Condition is FALSE Condition is TRUE

ISQS6337 JAVA

Jaeki Song

Decision Making

Looks Likerain

Wash car

Testcancelled

Study for test

NO

NO

YES

YES

ISQS6337 JAVA

Jaeki Song

if Structure

• Making a decision involves choosing between two alternative courses of action based on some value– The value upon which a decision is made is a

boolean value

booleanexpression

Resultingaction

Comparison operators (relational operator) are results in boolean values

ISQS6337 JAVA

Jaeki Song

Comparison Operators

<<=>>== =!=

less thanless than or equal togreater thangreater than or equal toequal tonot equal to

The boolean expression, e.g. (userResponse = = ‘Y’), must appear within parentheses

ISQS6337 JAVA

Jaeki Song

The if Statement

• Branch only if the condition is True

• Format

if (relational expression)

{ block of statements to be executed if

relational expression is true

}

ISQS6337 JAVA

Jaeki Song

The if Statement The else Clause

• Branch in one direction if test is True, another if False.

• Format:if (relational expression) { block of statements executed when True }else { block of statements executed when False }

ISQS6337 JAVA

Jaeki Song

Example

if (studentGrade >= 60) System.out.println (“ Passed”);else System.out.println (“Failed”) Grade >= 60 Print “passed”

true

false

ISQS6337 JAVA

Jaeki Song

The if Statement Nesting if Statements

• if and if-else statements can contain any valid JAVA statements, including other if or if-else statements.

• Placing an if or if-else within an if or if-else is called nesting.

• When nesting if-else statements within on another, care must be taken. The pairing of if’s and else’s can be tricky!

ISQS6337 JAVA

Jaeki Song

If..else and if…else if Statement

if (StudentGrade >= 90) System.out.println (“A”);else if (StudentGrade >= 80) System.out.println (“B”); else if (StudentGrade >= 70) System.out.println (“C”); else if (StudentGrade >= 60) System.out.println (“D”); else System.out.println(“F”);

if (StudentGrade >= 90) System.out.println (“A”);else if (StudentGrade >= 80) System.out.println (“B”);else if (StudentGrade >= 70) System.out.println (“C”);else if (StudentGrade >= 60) System.out.println (“D”);else System.out.println(“F”);

ISQS6337 JAVA

Jaeki Song

Example: Grade

ISQS6337 JAVA

Jaeki Song

AND and OR Operators

• Use AND operator (&&) within a boolean expression to determine whether two expression are both true.– Both boolean expression must be true before

the action in the statement can occur

if (itemSold > 3 && totalValue > 1000) bonus = 50;

ISQS6337 JAVA

Jaeki Song

AND and OR Operators

• Use OR operator (||) when you want some action ot occur even if only one of two conditions are true

// using two ifsif (itemSold > 100) bonus = 50;else if (totalValue > 1000) bonus = 50;

// Using OR operatorIf (itemSold > 100 | | totalValue > 3000) bonus 50;

ISQS6337 JAVA

Jaeki Song

Selection Logical Control Structure II

• Case control structure– Allow more than two choices when the condition

evaluated

Condition

Action 1 Action 1 Action 1 Action 1

Condition4 is TRUEConditio3 is TRUEConditio2 is TRUEConditio1 is TRUE

ISQS6337 JAVA

Jaeki Song

The switch Statement

• An alternative to the series of nested if statements

• Uses four keywords– switch: starts the structure and is followed

immediately by a test expression enclosed in parentheses.

– case: is followed by one of the possible values for the test expression and a colon

– break: optionally terminates a switch structure at the end of case

– default: optionally is used prior to any action that should occur if the test variable does not match any case

ISQS6337 JAVA

Jaeki Song

The switch Statement

if (year == 1) System.out.println (“Freshman”);else if (year = =2) System.out.println (“Sophomore”);else if (year = =3) System.out.println (“Junior”);else if (year = =4) System.out.println (“Senior”);else System.out.println(“ Invalid year”);

Switch (year){ case 1: System.out.prinln (“Freshman”); break; case 2: System.out.prinln (“Sophomore”); break; case 3: System.out.prinln (“Junior”); break; case 4: System.out.prinln (“Senior”); break;default: System.out.println (“Invalid year”);}

ISQS6337 JAVA

Jaeki Song

The switch Statement

• break statement– You can leave out the break statement in a

switch structure• When you omit the break, if the program find a

match for the test variable, the all statements within the switch statement form that point forward will execute

ISQS6337 JAVA

Jaeki Song

Example: Shipping Option

ISQS6337 JAVA

Jaeki Song

The Repetition Structure

• Repetition• Pre-Test Repetition

– Sentinel Value Loop

• Post-Test Repetition– Fixed-Count Loop

• Nested Loops

ISQS6337 JAVA

Jaeki Song

Repetition Logical Control Structure

• Allows for repeated execution of a set of statements based upon the outcome of a condition or test.– Also known as looping or iteration.

• Two components of a repetition structure:– Relational Expression or Test– Loop Body

ISQS6337 JAVA

Jaeki Song

Relational Expressions

• Relational expression– Set up as for Selection.– Always evaluates to either True (any non-zero

value) or False (a zero value).

• Body is executed as long as the test is True.

• Exit the loop when test is False.

ISQS6337 JAVA

Jaeki Song

Loop Body

• Is usually a block of code

• Contains instructions that reflect the task to be repeatedly performed;

• Can contain any valid Java statements

• Usually includes code so that the test will eventually prove False (or an infinite loop condition will result).

ISQS6337 JAVA

Jaeki Song

Pretest Repetition: while Statement

• Condition is tested before the body is ever executed.– Use a while loop to execute a body of

statements continuously while some condition continues to be true.

Booleanexpression

false

Loop bodytrue

ISQS6337 JAVA

Jaeki Song

The while Statement

• while loop can be used to implement pretest repetition

• Format:while (relational expression)

{ statements executed while test is True

} • Example

While (4 >2) System.out.println(“hello”) Infinite loop

ISQS6337 JAVA

Jaeki Song

The while Statement

• To prevent an infinite while loop– The loop control variable is initialized– The loop control variable is tested in the while statement– The body of the while statement must take some action that alter

the value of the loop control variable

• ExampleloopCount = 1;while (loopCount < 3){ System.out.println (“Hello”); loopCount = loopCount + 1;}

ISQS6337 JAVA

Jaeki Song

Increment and Decrement Operators

Increment Operators(all add 1 to the variable)

int icount = 0;

icount = icount + 1

icount += 1

icount++

++icount

Decrement Operators(all subtract 1 from the variable)

int dcounter = 0;

dcounter = dcounter - 1

dcounter -= 1

dcounter--

--dcounter

ISQS6337 JAVA

Jaeki Song

Example

• Class Average Program

ISQS6337 JAVA

Jaeki Song

Pretest Repetition; the for Statement

• for loop is counted loop and can also be used to implement pretest repetition– Use a while loop when you need to perform a task some

predetermined number of times– A loop that executes a specific number of time is a counted loop

• Format:for(initialization; expression; altering) { statements executed while condition is True }

• Example

for (int counter = 1; counter <=10 ; counter++)

Control variable name and initial value Increment of control variables

Loop condition and final value

ISQS6337 JAVA

Jaeki Song

Output Format

Pakage from java.text: import java.text.DecimalFormat;

DecimalFormat precisionTwo = new Decimal Format (“0.00”)

Pakage from javax.swing

import javax.swing.JTextArea;

JTextArea outputTextArea = new JTextArea (11,20)

Number of rows

Number of columns

ISQS6337 JAVA

Jaeki Song

Example: The for Repetition

ISQS6337 JAVA

Jaeki Song

Posttest Repetition: The do-while Statement

• Condition is tested after the body is executed;

• Body is always executed at least once;

• Often used for data validation, where data is validated as it is interactively entered.

ISQS6337 JAVA

Jaeki Song

The do-while Statement

• do-while loop is used to implement posttest repetition

• Format:

do {

statements executed while

condition is True

} while (relational expression);