400 likes | 1.17k Views
Chapter 7 Additional Control Structures. 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. Knowledge Goals.
E N D
Chapter 7 • Additional Control Structures
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
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
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
Skill Goals • Use the Java exception-handling facilities try, catch, and throw • Use a throw statement to throw a predefined exception
Switch Statement Switch 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
Switch Statement Switch expression Statement, beside Switch label that matches Switch expression, is executed
Switch Statement switch (digit) { case 1 : Statement1; break; case 2 : case 3 : Statement2; break; case 4 : Statement3; break; default: Statement4; } Statement5;
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
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
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; }
Do Statement do { Statement1; Statement2; … StatementN; } while (Expression); Called post-test loop because expression is tested at end of loop
Do Statement // Count-controlled repetition sum = 0; // initialize counter = 1; do { sum = sum + counter; counter++; // increment } while(counter <= 10);// condition Write an event-controlled loop that reads and sums until a 0 is found
Do Statement Understand the difference?
For Statement for (count = 1; count <= limit; count++) outFile.println("" + count);
For Statement Expression must be Boolean • Update can be • omitted • an expression • a series of expressions separate by commas • init can be • nothing • local variable declaration • an expression • a series of local variable declarations and expressions separated by commas
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
For Statement • What is output from this loop? • int count; • for (count = 1; count <= 10; count++); • System.out.println(“*”); Be careful!
For Statement • 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 Actually, the code outputs one *. Can you see why?
Guidelines for Looping Statements • For a simple count-controlled loop, use the for statement • For an event-controlled loop that must execute at least once, use the do statement • For an event-controlled loop about which nothing is known, use the while statement • When in doubt, use the while statement The while is the work horse of looping statements
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
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
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?
Java Operators • A further word about the assignment operator: When combined with its two operands, it forms an assignment expression • Assignment expression • A Java expression with (1) a value and (2) the side effect of storing the expression value into a memory location • Expression statement (assignment statement) • A statement formed by appending a semicolon to an assignment expression, an increment expression, or a decrement expression
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
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
Exceptions Code with exceptions Code to handle an exception Code to handle another exception
Execution of try-catch A statement throws an exception No statements throw an exception Exception Handler Control moves directly to exception handler Statements to deal with exception are executed Statement following entire try-catch statement
Exceptions try-catchwith 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 Same Always executes Yes, but how do you generate an exception?
Exceptions You generate an excepton by throwing it!
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
Exceptions An exception can be thrown in the block or any method called from within the block or any method called from within any method called …. try { // block } The system looks for a catch in the calling block. If not found, the method is exited and the next higher level block is searched. The process continues until a catch is found or the next level is the JVM.
Testing • Testing 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 checking • Tracing the execution of a design on paper • Walkthrough • A verification method in which a team performs a manual simulation of the code or design
Testing Inspection A verification method in which one member of a team reads the code or design lineby 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
Testing How many cases must your test plan include ?
Extras I became a professor of mathematics at age 22 and have a law named after me Who am I?
Extras - GUI Track Output from JOptionPane.showInputDialog
Extras - GUI Track Input read as a string; use Scanner to parse