[go: up one dir, main page]

0% found this document useful (0 votes)
57 views60 pages

Java and Software Design: Introduction To

The document discusses various control structures and logical operators in Java. It covers switch statements, do-while loops, for loops, break statements, conditional operators, logical operators, and exception handling. Some key points include: - Switch statements use a multiway branching structure to select among different case labels. - Do-while loops check the loop condition after executing the loop body, so the body is always executed at least once. - For loops contain an initialization, condition, and update section to control a loop. - Logical operators like && and || use short-circuit evaluation from left to right.

Uploaded by

Jayendra N Kadam
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views60 pages

Java and Software Design: Introduction To

The document discusses various control structures and logical operators in Java. It covers switch statements, do-while loops, for loops, break statements, conditional operators, logical operators, and exception handling. Some key points include: - Switch statements use a multiway branching structure to select among different case labels. - Do-while loops check the loop condition after executing the loop body, so the body is always executed at least once. - For loops contain an initialization, condition, and update section to control a loop. - Logical operators like && and || use short-circuit evaluation from left to right.

Uploaded by

Jayendra N Kadam
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

Introduction to

Java and Software Design


Dale

Weems

Headington

Chapter 10 Additional Control Structures and Exceptions


1

Slides by Sylvia Sorkin, The Community College of Baltimore County - Essex Campus

Chapter 10 Topics

switch Multiway Branching Structure do Statement for Looping for Statement for Looping break Statement
Bitwise Logical Operators Ternary and Assignment Operators Exception Handling using try and catch Defining Exception Classes
2

Switch Statement
Is a selection control structure for multiway branching. SYNTAX
switch ( IntegralExpression ) case Constant1 : Statement(s); case Constant2 : Statement(s);
. . .

// optional
// optional

default : Statement(s); }

// optional // optional
3

double char

weightInPounds = 165.8 ; weightUnit ; . . . // obtain letter for desired weightUnit switch ( weightUnit ) { case P : case p : System.out.println( Weight in pounds is + weightInPounds ) ; break ; case O : case o : System.out.println( Weight in ounces is + 16.0 * weightInPounds ) ; break ; case K : case k : System.out.println( Weight in kilos is + weightInPounds / 2.2 ) ; break ; case G : case g : System.out.println( Weight in grams is + 454.0 * weightInPounds ) ; break ; default : System.out.println( That unit is not handled! ) ; break ;
}
4

switch Structure

The value of IntegralExpression (of byte, char, short, or int type ) determines which branch is executed.

Case labels are constant ( possibly named ) integral expressions. Several case labels can precede a statement.

Control in switch Structure

Control branches to the statement following the case label that matches the value of IntegralExpression. Control proceeds through all remaining statements, including the default, unless redirected with break. If no case label matches the value of IntegralExpression, control branches to the default label, if present. Otherwise control passes to the statement following the entire switch structure.

Forgetting to use break can cause logical errors because after a branch is taken, control proceeds sequentially until either break or the end of the switch structure occurs.

break Statement

break statement can be used with switch or any of the 3 looping control structures. It causes an immediate exit from the switch, while, do, or for statement in which it appears. If the break is inside nested structures, control exits only the innermost structure containing it.
7

Count-controlled loop requires:


The name of a control variable (or loop counter). The initial value of the control variable. The increment (or decrement) by which the control variable is modified each time through the loop. The condition that tests for the final value of the control variable (to determine if looping should continue).
8

do Statement Syntax
Is a looping control structure in which the loop condition is tested after executing the body of the loop. DoStatement do Statement while ( Expression ) ;
Loop body can be a single statement or a block.
9

Using do to implement a count-controlled loop


// Count-controlled repetition sum = 0; counter = 1; do { sum = sum + counter; counter++; // increment // initialize

} while ( counter <= 10 );

// condition

10

do vs. while

POSTTEST loop (exit-condition) The loop condition is tested after executing the loop body. Loop body is always executed at least once.

PRETEST loop (entry-condition) The loop condition is tested before executing the loop body. Loop body may not be executed at all.
11

do Flowchart
DO Statement WHILE Expression true

false
When the expression is tested and found to be false, the loop is exited and control passes to the 12 statement that follows the do statement.

for Statement Syntax


ForStatement

for ( Init ; Expression ; Update ) Statement

13

A Count-Controlled Loop
SYNTAX
for ( initialization ; test expression ; update ) { 0 or more statements to repeat

}
14

The for statement contains


an Initialization a boolean Expression to test for continuing an Update to execute after each iteration of the loop body

15

Example of Repetition
int num; for ( num = 1 ; num <= 3 ; num++ ) { System.out.println( Potato + num ); }

16

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

17

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

18

num

Example of Repetition
true

int num;

for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

19

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1

20

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1

21

num

Example of Repetition
true

int num;

for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1

22

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1
Potato2
23

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1
Potato2
24

num

Example of Repetition
true

int num;

for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1
Potato2
25

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1
Potato2 Potato3
26

num

Example of Repetition

int num; for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1
Potato2 Potato3
27

num

Example of Repetition
false

int num;

for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num );


OUTPUT

Potato1
Potato2 Potato3
28

num

Example of Repetition
false

int num;

for ( num = 1 ; num <= 3 ; num++ )

System.out.println( Potato + num ); When the loop control condition is evaluated and has value false, the loop is said to be satisfied and control passes to the statement following the for structure.
29

The output was:


Potato1 Potato2 Potato3

30

What output from this loop?


int count;
for (count = 1; count <= 10; count++) ; System.out.println( * );

31

OUTPUT

No output from the for loop!

Why?

The ; right after the ( ) means that the body statement is a null statement In general, the body of the for loop is whatever statement immediately follows the ( ) That statement can be a single statement, a compound statement, or a null statement. Actually, the code outputs one * after the loop completes its counting from 1 to 11.

32

Another count-controlled loop


// Calculating compound interest double amount; double principal = 1000.0;

double rate = 0.07;


System.out.println(Year Amount);

for ( int year = 1; year <= 10; year++ ) { amount = principal * Math.pow( 1.0 + rate, year ); System.out.println(year + + amount); }

33

Java Has Combined Assignment Operators


int age ;

Write a statement to add 3 to age. age = age + 3 ;


OR,

age += 3 ;
34

Write a statement to subtract 10 from weight

int weight ;

weight = weight - 10 ;
OR,

weight -= 10 ;
35

Write a statement to divide money by 5.0

double money ;

money = money / 5.0 ;


OR,

money /= 5.0 ;
36

Write a statement to double profits

double profits ;

profits = profits * 2.0 ;


OR,

profits *= 2.0 ;
37

Write a statement to raise cost 15%


double cost; . . .

cost = cost + cost * .15 ;


OR,

cost = 1.15 * cost;


OR,

cost *= 1.15 ;
38

Which form to use?

When the increment (or decrement) operator is used in a stand alone statement solely to add one (or subtract one) from a variables value, it can be used in either prefix or postfix form.
USE EITHER

dogs-- ;

--dogs;
39

BUT...

When the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results.
LETS SEE HOW. . .

40

PREFIX FORM First increment, then use


int alpha ; int num ; 13

num = 13;
alpha = ++num * 3;

num

alpha

14
num

14
num

42
alpha
41

POSTFIX FORM Use, then increment


int alpha ; int num ;
num = 13; alpha = num++ * 3;

13
num alpha

13
num

39
alpha

14
num
42

Operators can be
binary
unary ternary

involving 2 operands
involving 1 operand involving 3 operands

2+3
-3 follows

43

Conditional (Ternary) Operator ? :


SYNTAX
Expression1 ? Expression2 : Expression3

MEANING If Expression1 is true, then the value of the entire expression is Expression2. Otherwise, the value of the entire expression is Expression 3.

FOR EXAMPLE . . .

44

Using Conditional Operator


// Finds the smaller of two float values double double double . . . min = ( x < y ) ? x : y ; min ; x; y;

45

Control Structures
Use logical expressions which may include: 6 Relational Operators

<

<=

>

>=

==

!=

6 Logical Operators

&&

||

&

|
46

LOGICAL EXPRESSION
p |q

MEANING Bitwise logical inclusive OR Bitwise logical AND

DESCRIPTION p | q is false if both p and q are false. It is true otherwise. p & q is true if both p and q are true. It is false otherwise.

p&q

p ^q

Bitwise logical exclusive OR

p ^ q is true only if p and q have different boolean values. It is false otherwise. 47

Short-Circuit Evaluation

Java uses short circuit evaluation of logical expressions involving && and ||. This means logical expressions with && and || are evaluated left to right and evaluation stops as soon as the correct boolean value of the entire expression is known.

Expressions involving & and | work identically to those involving && and || with the exception that both operands are always evaluated (there is no shortcircuit evaluation).
48

Precedence (highest to lowest)


Operator () unary: ++ -- ! + - (cast) * / % + < <= > >= == != & ^ | && || ?: = += -= *= /= %= Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left
49

try-catch-finally
try {
. . . // Statements that try to open a file } catch (IOException except) { . . . // Statements execute if cant open file } finally { . . . // Statements are always executed }
50

try-catch Example
filename = fileField.getText( ); try { outFile = new PrintWriter(new FileWriter(filename)); } catch (IOException except) { errorLabel.setText(Unable to open file + filename); fileField.setText(); }

51

Three Part Exception Handling

Defining the exception By extending type Exception and supplying a pair of constructors that call super Raising (generating) the exception By use of the throw statement Handling the exception By use of a throws clause specifying the type of exception being forwarded or, By use of try-catch-finally to catch an exception. 52

Rainfall CRC Card


Class Name: Incomes Responsibilities Prepare the file for input Prepare the file for output Superclass: Object Subclasses:

Collaborations FileReader, BufferedReader FileWriter, PrintWriter

Process data
Throw exceptions if necessary

BufferedReader
DataSetException
53

Defining an Exception Class


// Defines an Exception class for signaling data set errors rainfall; package

class DataSetException extends Exception { public DataSetException( ) { super( ); } public DataSetException( String message ) { super( message ); } }
54

// // //

Inputs 12 monthly rainfall amounts from a file and computes the average monthly rainfall. This process is repeated for any number of recording sites.

package rainfall; import java.io.*; public class Rainfall { static void processOneSite( BufferedReader infile, PrintWriter outFile, String dataSetName ) { int count; // Loop control variable double amount; // Rain for one month double sum = 0.0; // Sums annual rainfall String dataLine; // Input from inFile String currentValue; // String for numeric int index; // Position of blank try { // Could produce an IOException dataLine = inFile.readLine( ); 55

for (count = 1; cout <= 12; count++) { // Find position of blank index = dataLine.indexOf( ); if (index > 0) { // Blank found currentValue = dataLine.substring(0, index); dataLine = dataLine.substring( Math.min(index+1, dataLine.length()), dataLine.length( )); } else // Remaining string is current value currentValue = dataLine; amount = Double.valueOf (currentValue).doubleValue( ); if (amount < 0.0) throw new DataSetException(Negative in ); else sum = sum + amount; 56 }

outFile.println( Average for + dataSetName + is + sum/12.0 );


} catch (IOException except) { outFile.println(IOException with site + dataSetName); System.exit(0); } catch (NumberFormatException except) { outFile.println(NumberFormatException in site + dataSetName); } catch (DataSetException except) { outFile.println(except.getMessage( ) + dataSetName); } }

57

public static void main( String[ ] args ) throws FileNotFoundException, IOException { String dataSetName; inFile; // Reporting station name // Data file BufferedReader

PrintWriter

outFile;

// Output file

inFile = new BufferedReader( new FileReader(rainData.dat)); outFile = new PrintWriter( new FileWriter(outfile.dat)); // Get name of reporting station dataSetName = inFile.readLine( );
58

Rainfall Application
// Processing Loop do { processOneSite(inFile, outFile, dataSetName); dataSetName = infile.readLine( ); } while (dataSetName != null); inFile.close( ); outLine.close( ); System.exit(0); } }
59

ACKNOWLEDGMENT:
This project was supported in part by the National Science Foundation under award DUE-ATE 9950056. Opinions are those of the authors and do not necessarily reflect the views of the National Science Foundation.

60

You might also like