Core Java Volume I — 3.8. Control Flow
3.8. Control Flow
Java, like any programming language, supports both conditional statements and loops to determine control flow. We will start with the conditional statements, then move on to loops, to end with the somewhat cumbersome switch statement that you can use to test for many values of a single expression.
C++ Note
The Java control flow constructs are identical to those in C and C++, with a few exceptions. There is no goto, but there is a "labeled" version of break that you can use to break out of a nested loop(Java中没有goto语句,可以使用带标签的break语句来跳出嵌套的循环) (where, in C, you perhaps would have used a goto). Finally, there is a variant of the for loop that has no analog in C or C++. It is similar to the foreach loop in C#.
3.8.1. Block Scope
Before we get into the actual control structures, you need to know more about blocks. A block or compound statement(复合语句) is any number of simple Java statements surrounded by a pair of braces(大括号). Blocks define the scope of your variables. A block can be nested inside another block. Here is a block that is nested inside the block of the main method.
public static void main(String[] args)
{
int n;
. . .
{
int k;
. . .
} // k is only defined up to here
}
However, you may not declare identically named variables in two nested blocks(在两个嵌套的语句块中,不可以定义相同名字的变量). For example, the following is an error and will not compile:
public static void main(String[] args)
{
int n;
. . .
{
int k;
int n; // ERROR--can't redefine n in inner block
. . .
}
}
C++ Note
In C++, it is possible to redefine a variable inside a nested block. The inner definition then shadows the outer one. This can be a source of programming errors; hence, Java does not allow it.
3.8.2. Conditional Statements
The conditional statement in Java has the form
if (condition) statement
The condition must be surrounded by parentheses(圆括号).
In Java, as in most programming languages, you will often want to execute multiple statements when a single condition is true. In this case, use a block statement that takes the form
{
statement1
statement2
. . .
}
For example:
if (yourSales >= target)
{
performance = "Satisfactory";
bonus = 100;
}
In this code all the statements surrounded by the braces will be executed when yourSales is greater than or equal to target (see Figure 3.7).
Note
A block (sometimes called a compound statement) allows you to have more than one (simple) statement in any Java programming structure that otherwise allows for a single (simple) statement.
The more general conditional in Java looks like this (see Figure 3.8):
if (condition) statement1 else statement2
For example:
if (yourSales >= target)
{
performance = "Satisfactory";
bonus = 100 + 0.01 * (yourSales - target);
}
else
{
performance = "Unsatisfactory";
bonus = 0;
}
The else part is always optional. An else groups with the closest if(else与最接近的if为一组). Thus, in the statement
if (x <= 0) if (x == 0) sign = 0; else sign = -1;
the else belongs to the second if. Of course, it is a good idea to use braces to clarify this code:
if (x <= 0) { if (x == 0) sign = 0; else sign = -1; }
Repeated if . . . else if . . . alternatives are common (see Figure 3.9). For example:
if (yourSales >= 2 * target)
{
performance = "Excellent";
bonus = 1000;
}
else if (yourSales >= 1.5 * target)
{
performance = "Fine";
bonus = 500;
}
else if (yourSales >= target)
{
performance = "Satisfactory";
bonus = 100;
}
else
{
System.out.println("You're fired");
}
3.8.3. Loops
The while loop executes a statement (which may be a block statement) while a condition is true. The general form is :
while (condition) statement
The while loop will never execute if the condition is false at the outset (see Figure 3.10).
The program in Listing 3.3 determines how long it will take to save a specific amount of money for your well-earned retirement, assuming you deposit the same amount of money per year and the money earns a specified interest rate.
In the example, we are incrementing a counter and updating the amount currently accumulated in the body of the loop until the total exceeds the targeted amount.
while (balance < goal)
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
System.out.println(years + " years.");
(Don't rely on this program to plan for your retirement. We left out a few niceties such as inflation and your life expectancy.)
A while loop tests at the top. Therefore, the code in the block may never be executed. If you want to make sure a block is executed at least once, you will need to move the test to the bottom, using the do/while loop. Its syntax looks like this:
do statement while (condition);
This loop executes the statement (which is typically a block) and only then tests the condition. If it's true, it repeats the statement and retests the condition, and so on. The code in Listing 3.4 computes the new balance in your retirement account and then asks if you are ready to retire:
do
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
// print current balance
. . .
// ask if ready to retire and get input
. . .
}while (input.equals("N"));
As long as the user answers "N", the loop is repeated (see Figure 3.11). This program is a good example of a loop that needs to be entered at least once, because the user needs to see the balance before deciding whether it is sufficient for retirement.
Listing 3.3. Retirement/Retirement.java
Listing 3.4. Retirement2/Retirement2.java
3.8.4. Determinate Loops
The for loop is a general construct to support iteration(迭代) controlled by a counter or similar variable that is updated after every iteration. As Figure 3.12 shows, the following loop prints the numbers from 1 to 10 on the screen.
for (int i = 1; i <= 10; i++)
System.out.println(i);
The first slot of the for statement usually holds the counter initialization. The second slot gives the condition that will be tested before each new pass through the loop, and the third slot specifies how to update the counter.
Although Java, like C++, allows almost any expression in the various slots of a for loop, it is an unwritten rule of good taste that the three slots should only initialize, test, and update the same counter variable. One can write very obscure loops by disregarding this rule.
Even within the bounds of good taste, much is possible. For example, you can have loops that count down:
for (int i = 10; i > 0; i--)
System.out.println("Counting down . . . " + i);
System.out.println("Blastoff!");
Caution
Be careful about testing for equality of floating-point numbers in loops. A for loop like this one
for (double x = 0; x != 10; x += 0.1) . . .
may never end. Because of roundoff errors, the final value may not be reached exactly. In this example, x jumps from 9.99999999999998 to 10.09999999999998 because there is no exact binary representation for 0.1.
When you declare a variable in the first slot of the for statement, the scope of that variable extends until the end of the body of the for loop.
for (int i = 1; i <= 10; i++)
{
. . .
}
// i no longer defined here
In particular, if you define a variable inside a for statement, you cannot use its value outside the loop. Therefore, if you wish to use the final value of a loop counter outside the for loop, be sure to declare it outside the loop header!
int i;
for (i = 1; i <= 10; i++)
{
. . .
}
// i is still defined here
On the other hand, you can define variables with the same name in separate for loops:
for (int i = 1; i <= 10; i++)
{
. . .
}
. . .
for (int i = 11; i <= 20; i++) // OK to define another variable named i
{
. . .
}
A for loop is merely a convenient shortcut for a while loop. For example,
for (int i = 10; i > 0; i--)
System.out.println("Counting down . . . " + i);
can be rewritten as
int i = 10;
while (i > 0)
{
System.out.println("Counting down . . . " + i);
i--;
}
Listing 3.5 shows a typical example of a for loop.
The program computes the odds of winning a lottery. For example, if you must pick six numbers from the numbers 1 to 50 to win, then there are (50 × 49 × 48 × 47 × 46 × 45)/(1 × 2 × 3 × 4 × 5 × 6) possible outcomes, so your chance is 1 in 15,890,700. Good luck!
Listing 3.5. LotteryOdds/LotteryOdds.java
In general, if you pick k numbers out of n, there are
n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
possible outcomes. The following for loop computes this value:
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
l otteryOdds = lotteryOdds * (n - i + 1) / i;
Note
See Section 3.10.1, "The "for each" Loop," on p. 109 for a description of the "generalized for loop" (also called "for each" loop) that was added to the Java language in Java SE 5.0.
3.8.5. Multiple Selections—The switch Statement
The if/else construct can be cumbersome when you have to deal with multiple selections with many alternatives. Java has a switch statement that is exactly like the switch statement in C and C++, warts and all.
For example, if you set up a menuing system with four alternatives like that in Figure 3.13, you could use code that looks like this:
Scanner in = new Scanner(System.in);
System.out.print("Select an option (1, 2, 3, 4) ");
int choice = in.nextInt();
switch (choice)
{
case 1:
. . .
break;
case 2:
. . .
break;
case 3:
. . .
break;
case 4:
. . .
break;
default:
// bad input
. . .
break;
}
Execution starts at the case label that matches the value on which the selection is performed and continues until the next break or the end of the switch. If none of the case labels match, then the default clause is executed, if it is present.
Caution
It is possible for multiple alternatives to be triggered. If you forget to add a break at the end of an alternative, then execution falls through to the next alternative! This behavior is plainly dangerous and a common cause for errors. For that reason, we never use the switch statement in our programs.
If you like the switch statement better than we do, consider compiling your code with the -Xlint:fallthrough option, like this:
javac -Xlint:fallthrough Test.java
Then the compiler will issue a warning message whenever an alternative does not end with a break statement.
If you actually want to use the fallthrough behavior, tag the surrounding method with the annotation @SuppressWarnings("fallthrough"). Then no warnings will be generated for that method. (An annotation is a mechanism for supplying information to the compiler or a tool that processes Java source or class files. We will discuss annotations in detail in Chapter 13 of Volume II.)
A case label can be
- A constant expression of type char, byte, short, or int (or their corresponding wrapper classes Character, Byte, Short, and Integer that will be introduced in Chapter 4)
- An enumerated constant
- Starting with Java SE 7, a string literal
For example,
String input = . . .;
switch (input.toLowerCase())
{
case "yes": // OK since Java SE 7
. . .
break;
. . .
}
When you use the switch statement with enumerated constants, you need not supply the name of the enumeration in each label(使用枚举变量时,不需要在每个case标签中都加上枚举变量名)—it is deduced from the switch value. For example:
Size sz = . . .;
switch (sz)
{
case SMALL: // no need to use Size.SMALL
. . .
break;
. . .
}
3.8.6. Statements That Break Control Flow
Although the designers of Java kept goto as a reserved word, they decided not to include it in the language. In general, goto statements are considered poor style. Some programmers feel the anti-goto forces have gone too far (see, for example, the famous article of Donald Knuth called "Structured Programming with goto statements"). They argue that unrestricted use of goto is error-prone but that an occasional jump out of a loop is beneficial. The Java designers agreed and even added a new statement, the labeled break, to support this programming style.
Let us first look at the unlabeled break statement. The same break statement that you use to exit a switch can also be used to break out of a loop. For example:
while (years <= 100)
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if (balance >= goal) break;
years++;
}
Now the loop is exited if either years > 100 occurs at the top of the loop or balance >= goal occurs in the middle of the loop. Of course, you could have computed the same value for years without a break, like this:
while (years <= 100 && balance < goal)
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if (balance < goal)
years++;
}
But note that the test balance < goal is repeated twice in this version. To avoid this repeated test, some programmers prefer the break statement.
Unlike C++, Java also offers a labeled break statement that lets you break out of multiple nested loops(带标签的break语句,用于跳出多个嵌套循环). Occasionally something weird happens inside a deeply nested loop. In that case, you may want to break completely out of all the nested loops. It is inconvenient to program that simply by adding extra conditions to the various loop tests.
Here's an example that shows the break statement at work. Notice that the label must precede the outermost loop out of which you want to break. It also must be followed by a colon(标签必须在循环的最外层,后面需要带一个冒号).
Scanner in = new Scanner(System.in);
int n;
read_data:
while (. . .) // this loop statement is tagged with the label
{
. . .
for (. . .) // this inner loop is not labeled
{
System.out.print("Enter a number >= 0: ");
n = in.nextInt();
if (n < 0) // should never happen—can't go on
break read_data;
// break out of read_data loop
. . .
}
}
// this statement is executed immediately after the labeled break
if (n < 0) // check for bad situation
{
// deal with bad situation
}
else
{
// carry out normal processing
}
If there was a bad input, the labeled break moves past the end of the labeled block. As with any use of the break statement, you then need to test whether the loop exited normally or as a result of a break.
Note
Curiously, you can apply a label to any statement, even an if statement or a block statement(甚至可以在if语句或者语句块中使用标签break), like this:
label:
{
. . .
if (condition) break label; // exits block
. . .
}
// jumps here when the break statement executes
Thus, if you are lusting after a goto and if you can place a block that ends just before the place to which you want to jump, you can use a break statement! Naturally, we don't recommend this approach. Note, however, that you can only jump out of a block, never into a block(只能跳出一个语句块,不能跳进一个语句块).
Finally, there is a continue statement that, like the break statement, breaks the regular flow of control. The continue statement transfers control to the header of the innermost enclosing loop. Here is an example:
Scanner in = new Scanner(System.in);
while (sum < goal)
{
System.out.print("Enter a number: ");
n = in.nextInt();
if (n < 0) continue;
sum += n; // not executed if n < 0
}
If n < 0, then the continue statement jumps immediately to the loop header, skipping the remainder of the current iteration.
If the continue statement is used in a for loop, it jumps to the "update" part of the for loop. For example:
for (count = 1; count <= 100; count++)
{
System.out.print("Enter a number, -1 to quit: ");
n = in.nextInt();
if (n < 0) continue;
sum += n; // not executed if n < 0
}
If n < 0, then the continue statement jumps to the count++ statement.
There is also a labeled form of the continue statement that jumps to the header of the loop with the matching label.
Tip
Many programmers find the break and continue statements confusing. These statements are entirely optional—you can always express the same logic without them. In this book, we never use break or continue.
Core Java Volume I — 3.8. Control Flow的更多相关文章
- Core Java Volume I — 1.2. The Java "White Paper" Buzzwords
1.2. The Java "White Paper" BuzzwordsThe authors of Java have written an influential White ...
- Core Java Volume I — 4.7. Packages
4.7. PackagesJava allows you to group classes in a collection called a package. Packages are conveni ...
- Core Java Volume I — 5.1. Classes, Superclasses, and Subclasses
5.1. Classes, Superclasses, and SubclassesLet's return to the Employee class that we discussed in th ...
- Core Java Volume I — 4.4. Static Fields and Methods
4.4. Static Fields and MethodsIn all sample programs that you have seen, the main method is tagged w ...
- Core Java Volume I — 3.10. Arrays
3.10. ArraysAn array is a data structure that stores a collection of values of the same type. You ac ...
- Core Java Volume I — 3.1. A Simple Java Program
Let’s look more closely at one of the simplest Java programs you can have—one that simply prints a m ...
- Core Java Volume I — 4.10. Class Design Hints
4.10. Class Design HintsWithout trying to be comprehensive or tedious, we want to end this chapter w ...
- Core Java Volume I — 4.6. Object Construction
4.6. Object ConstructionYou have seen how to write simple constructors that define the initial state ...
- Core Java Volume I — 4.5. Method Parameters
4.5. Method ParametersLet us review the computer science terms that describe how parameters can be p ...
随机推荐
- discuzx3.1中引用 Jquery报错的解决办法
我们可以引用jQuery给JQ赋予一个变量var jq = jQuery.noConflict(); 修改成为:<script type="text/javascript"& ...
- hduacm 2888 ----二维rmq
http://acm.hdu.edu.cn/showproblem.php?pid=2888 模板题 直接用二维rmq 读入数据时比较坑爹 cin 会超时 #include <cstdio& ...
- Hello Struts2
Struts2 概述 Struts2 是一个用来开发 MVC 应用程序的框架. 它提供了 Web 应用程序开发过程中的一些常见问题的解决方案: 对来自用户的输入数据进行合法性验证; 统一的布局; 可扩 ...
- MonoRail学习-入门实例篇
1.到官方网站下载安装文件,地址如下: http://www.castleproject.org/index.php/Castle:Download目前最新版本Beta5(您也可以不需要下载,直接使用 ...
- 《JAVA笔记 day08 静态_单例》
//static关键字: /* 静态方法的使用注意事项: 1,静态方法不能访问非静态的成员. 但是非静态是可以访问静态成员的. 说明:静态的弊端在于访问出现了局限性.好处是可以直接别类名调用. 2,静 ...
- PAT 07-0 写出这个数
用拼音输出一个数字的各位数字之和,这个或许比上面的标题恰当.这里我第一次用到了sprintf()(stdio.h)这个函数,我本来是要找itoa()(stdlib.h)函数来着,查资料一看,说这个函数 ...
- oracle 备份和还原还有创建用户、表空间、授权
--找到存放dbf文件的路径--E:\oracle\product\10.2.0\oradata\orcl--可以通过此语句进行查询select * from v$datafile; --创建表空间c ...
- hdu 2055
PS:上课的时候敲的..这道题简单..一次AC,不多说了.. 代码: #include "stdio.h"int main(){ int i,n,y; char x,a[26],b ...
- 2016-1-8 Quartz框架的学习,多个气球上升的小动画
// // BallonView.m // 气球上升的动画 // // Created by Mac on 16/1/8. // Copyright © 2016年 Mac. All rights r ...
- 将salt取到的数据处理
#!/usr/bin/env python #coding:utf-8 import json with open('minfo') as f,open('minfoMiddle','w') as f ...