首页 > 代码库 > CoreJavaE10V1P3.8 第3章 Java的基本编程结构-3.8 控制流程(Control Flow)

CoreJavaE10V1P3.8 第3章 Java的基本编程结构-3.8 控制流程(Control Flow)

通过使用条件语句、循环语句可以实现流程的控制。

3.8.1 块作用域(Block Scope)

块(Block)就是由一对花括号包围起来的部分。他指定了一个变量的生存范围,与一个方法的操作范围。 Java中不允许在嵌套块中重复定义变量。

3.8.2 条件语句

if (condition) statement 

{
statement 1
statement 2
. . .
}
if (yourSales >= target)
{
performance = "Satisfactory";
bonus = 100 + 0.01 * (yourSales - target);
}
else
{
performance = "Unsatisfactory";
bonus = 0;
}
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  循环语句

1.while 循环

while (condition) statement

while (balance < goal)
{
    balance += payment;
    double interest = balance * interestRate / 100;
    balance += interest;
    years++;
}
System.out.println(years + " years.");

2.do-while 循环

do statement while (condition); 注意有;。

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"));

3.8.4 固定次数循环(Determinate loop)

1.for循环

for (int i = 10; i > 0; i--)
    System.out.println("Counting down . . . " + i);

3.8.5 多重选择 Switch 语句

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;
}

Case 标签(即Switch后跟的变量类型)可以是:

?  char , byte , short ,  int 及其包装类的常量表达式
? 枚举类型
? 从Java SE 7开始支持string 字面值。

String input = . . .;
switch (input.toLowerCase())
{
case "yes": // OK since Java SE 7
. . .
break;
. . .
}

3.8.6 跳出循环

1.虽然Java保留的goto关键字,但是不推荐使用goto语句。一般使用break跳出循环。Java支持带标签的break语句,用于跳出多重循环。相当于给每个循环起个名字,跳出时可以指定跳出哪个循环。

label:
{
. . .
if (condition) break label; // exits block
. . .
}
// jumps here when the break statement executes

示例如下:

while (years <= 100)
{
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if (balance >= goal) break;
years++;
}
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
. . .
}
}

 

2.continue 语句

 跳出本次循环

 

CoreJavaE10V1P3.8 第3章 Java的基本编程结构-3.8 控制流程(Control Flow)