1 chapter 7 additional control structures. 2 knowledge goals understand the role of the switch...
Post on 21-Dec-2015
219 views
TRANSCRIPT
1
Chapter 7
Additional Control Structures
2
Knowledge Goals
• Understand the role of the switch statement
• Understand the purpose of the break statement
• Understand the distinctions among the alternative looping statements
• Understand what is and what is not an exception
3
Knowledge Goals
• Know when throwing an exception is appropriate
• Know how an exception should be handled
• Be aware of Java's additional operators and their place in the precedence hierarchy with respect to one another
4
Skill Goals
• Write a switch statement for a multiway branching problem
• Write a do statement and contrast it with a while statement
• Write a for statement as an alternative to a while statement
• Choose the most appropriate looping statement for a given problem
5
Skill Goals
• Use the Java exception-handling facilities try, catch, and throw
• Use a throw statement to throw a predefined exception
6
Switch StatementSwitch statement
A selection control structure for multiway branching
Switch label
"case" + constant which labels a code segment
Switch expression
The integral expression whose value determines which switch label is selected
7
Switch Statement
Switch expression
Statement, besideSwitch label
that matches Switchexpression, is
executed
8
Switch Statement
switch (digit)
{
case 1 : Statement1;
break;
case 2 :
case 3 : Statement2;
break;
case 4 : Statement3;
break;
default: Statement4;
}
Statement5;
9
Switch Statement
The value of IntegralExpression (Switch expression) that determines which branch is executed must be of types byte, char, short, or int
Case labels are constant (possibly named) integral expressions; several case labels can be associated with a statement
10
Switch Statement
Summary of flow of control Control branches to the statement associated with the case
label that matches the value of the integral switch expression
Control proceeds through all remaining statements, including the default, unless redirected with break
If no case label matches the value of the switch expression, 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
11
double weightInPounds = 165.8;char weightUnit;System.out.print(“Weight in “);switch (weightUnit) { case ‘P’ : case ‘p’ : System.out.println(“pounds is “ + weightInPounds); break; case ‘O’ : case ‘o’ : System.out.println(“ounces is “ + 16.0*weightInPounds); break; case ‘K’ : case ‘k’ : System.out.println(“kilos is “ + weightInPounds/2.2); break; case ‘G’ : case ‘g’ : System.out.println(“grams is “ + 454.0*weightInPounds); break; default : System.out.println(“That unit is not handled!”); break;}
12
Do Statement
do
{
Statement1;
Statement2;
…
StatementN;
} while (Expression);
Called post-test loop because expression is tested at end of loop
13
// Count-controlled repetition sum = 0; // initialize counter = 1;
do {
sum = sum + counter;
counter++; // increment
} while(counter <= 10); // condition
Do Statement
Write an event-controlled loop that reads and sums until a 0 is found
14
Do Statement
Understand the difference?
15
For Statement
for (count = 1; count <= limit; count++)
outFile.println("" + count);
16
For Statement
init can be nothing local variable declaration an expression a series of local variable
declarations and expressions separated by commas
Expression must be Boolean
Update can be omitted an expression a series of
expressions separate by commas
17
For Statement
int num;
for (num = 1; num <= 3; num++)
{
System.out.println(“Potato “ + num);
}
Trace:
num num<=3 printed:
1 1<=3 Potato 1
2 2<=3 Potato 2
3 3<=3 Potato 3
4 4<=3 nothing
18
For Statement
What is output from this loop? int count;
for (count = 1; count <= 10; count++);
System.out.println(“*”);
Be careful!
19
Did you say no output from the for loop?The semicolon right after the parentheses means that the body statement is a null statement
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
For Statement
Actually, the code outputs one *.
Can you see why?
20
Guidelines for Looping Statements
1. For a simple count-controlled loop, use the for statement
2. For an event-controlled loop that must execute at least once, use the do statement
3. For an event-controlled loop about which nothing is known, use the while statement
4. When in doubt, use the while statement
The while is the work horse of looping statements
21
Break Statement
Break statement
A control statement that causes an immediate exit from the statement in which it appears
If inside a nested structures, control exits only the innermost structure containing it
Can be used in a switch statement and any looping statements
22
Continue Statement
Continue statement
A control statement that causes a loop to jump to the start of the next iteration
Can only be used in a looping statement
23
Java Operators
We have examined arithmetic operators relational operators logical operators (both full and short-circuit
evaluation increment and decrement operators assignment operator see the back of the book for additional operators
that make some operations easier
Can you give the symbols for each of these?
24
Java Operators
A further word about the assignment operator: When combined with its two operands, it forms an assignment expressionAssignment expressionA Java expression with (1) a value and (2) the side effect of storing the expression value into a memory locationExpression statement (assignment statement)A statement formed by appending a semicolon to an assignment expression, an increment expression, or a decrement expression
25
Exceptions
• Recall that an exception is an unusual
situation that occurs when a program is
running
• So far we have "passed the buck" by
throwing the exceptions to the next level
• Now we show how to manage our own
exceptions
26
Exceptions
Exception Management
The process of defining and taking care of exceptions, which includes
defining the exception (determining what is and is not an exception)
raising (throwing) the exception (recognizing when it occurs)
handling the exception (code that is executed when an exception is caught)
try-catch-finally statement allows all this
27
Exceptions
Code with exceptions
Code to handle an exception
Code to handle another exception
28
Execution of try-catch
No statements throw
an exception
Statement following entire try-catch
statement
A statement throws
an exception
Exception Handler
Statements to deal with exception are executed
Control moves directly to exception handler
29
try-catch with Built-In Exception
Scanner in = new Scanner(System.in); System.out.println("Enter file name"); String filename = in.nextLine();
try
{
Scanner inFile = new Scanner(new FileReader(filename));
}
catch(IOException except)
{
System.out.println(“Unable to open file ” + filename);
}
Exceptions
30
Exceptions
Same
Always executes
Yes, but how do you generate an exception?
31
Exceptions
You generate an excepton by throwing it!
32
Exceptions
try
{
if (someproblem)
throw new Exception("You have problems");
}
catch(Exception except)
{
System.out.println("Exception throw: " +
except.getMessage());
}
getMessage is method in class Exception ;it returns the constructor's argument
33
Exceptions
34
Exceptions
try
{
// block
}
An exception can bethrown in the block
or any method called from within the block or
any method calledfrom within any
method called ….
The system looks for a catch in the calling block. If notfound, the method is exited and the next higher level
block is searched. The process continues until acatch is found or the next level is the JVM.
35
TestingTesting axioms:
An application or class is never finished until it has been thoroughly tested!
Testing activities begin at the design stage and run in parallel with design and implementation
Desk checkingTracing the execution of a design on paperWalkthroughA verification method in which a team performs a manual simulation of the code or design
36
Testing
Inspection
A verification method in which one member of a team reads the code or design line by line and the other team members point out errors
Execution trace
Going through the code with actual values, recording the state of the variables
Hint: Use data from your test plan in your execution trace
37
Testing
How manycases
must yourtest planinclude
?
38
Extras
I became aprofessor ofmathematicsat age 22 and
have a lawnamed
after me
Who am I?
39
Extras - GUI Track
Output from JOptionPane.showInputDialog
40
Extras - GUI Track
Input read as a string; use Scanner to parse