tailieunhanh - Lecture Data structures and algorithms in Java (6th edition): Chapter 1(continue) - Goodrich, Tamassia, Goldwasser

Java Primer 2 - I/O methods and control flow. Control flow in Java is similar to that of other high-level languages. We review the basic structure and syntax of control flow in Java in this section, including method returns, if statements, switch statements, loops, and restricted forms of “jumps” (the break and continue statements). | Java Primer 2 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 2: I/O Methods and Control Flow © 2014 Goodrich, Tamassia, Goldwasser Java Primer 2 1 If Statements q   q   The syntax of a simple if statement is as follows: booleanExpression is a boolean expression and trueBody and falseBody are each either a single statement or a block of statements enclosed in braces (“{” and “}”). © 2014 Goodrich, Tamassia, Goldwasser Java Primer 2 2 1 Java Primer 2 3/18/14 Compound if Statements q   There is also a way to group a number of boolean tests, as follows: © 2014 Goodrich, Tamassia, Goldwasser Java Primer 2 3 Switch Statements q   q   q   q   Java provides for multiple-value control flow using the switch statement. The switch statement evaluates an integer, string, or enum expression and causes control flow to jump to the code location labeled with the value of this expression. If there is no matching label, then control flow jumps to the location labeled “default.” This is the only explicit jump performed by the switch statement, however, so flow of control “falls through” to the next case if the code for a case is not ended with a break statement © 2014 Goodrich, Tamassia, Goldwasser Java Primer 2 4 2 Java Primer 2 3/18/14 Switch Example © 2014 Goodrich, Tamassia, Goldwasser Java Primer 2 5 Break and Continue q   q   Java supports a break statement that immediately terminate a while or for loop when executed within its body. Java also supports a continue statement that causes the current iteration of a loop body to stop, but with subsequent passes of the loop proceeding as expected. © 2014 Goodrich, Tamassia, Goldwasser Java Primer 2 6 3 Java Primer 2 3/18/14 While Loops q   q   q   The simplest kind of loop in Java is a while loop. Such a loop tests that a certain condition is satisfied .