Loops in Java--循环语句

In this session, we will learn different types of loop statements in Java and will see how to use them in a program.

本节课我们将学习多种循环语句并进行代码实现。

Opening Problem

问题导入

Suppose you need to display a string (e.g. Welcome to Java!) a hundred times.

假如你要输出"Welcome to Java!"一百次。

It would be tedious to have to write the statement shown in this slide a hundred times, so how to solve this problem?
我们不可能写100行输出语句,那么如何解决这个问题呢?

Java provides a powerful construct called a loop that controls how many times an operation or a sequence of operations is performed in succession.

Java提供了一种能够控制操作执行次数的结构--循环语句。

Using a loop statement, you can simply tell the computer to display a string a hundred times without having to code the print statement a hundred times.

用循环语句可以轻松实现打印一个字符串100次的操作,而不用写100行输出语句。

Introducing while Loops

while循环

int count=0;
        while (count<100){
            System.out.println("Welcome to Java");
            count++;
        }

As is shown in the code above, the variable count is initially 0.

上面这段代码中,变量count初始化为0。

The loop checks whether count < 100 is true.

这个循环就会检查是否满足count < 100。

If so, it executes the loop body to display the message Welcome to Java! and increments count by 1.

如果满足,循环体里面的打印语句执行一次,输出Welcome to Java!,然后count加1。

It repeatedly executes the loop body until count < 100 becomes false.

然后再执行这个循环体直到不满足count < 100的条件。

When count < 100 is false (when count reaches 100), the loop terminates, and the next statement after the loop statement is executed.

当count < 100不满足时,也就是count达到100的时候,循环终止并继续执行这个循环后续的语句。

Loops are constructs that control repeated executions of a block of statements.

循环是一种控制某一语句块重复执行的结构。

The concept of looping is fundamental to programming.

循环的概念是编程的基础。

Java provides three types of loop statements: while loops, do-while loops, and for loops.

Java提供三种循环语句:while循环、do-while循环和for循环。

flowchart of while loop

while循环的流程图

The syntax for the while loop is shown on the left-top side of this slide.

while循环的语法如下。

 while (loop-continuation-condition){
            // loop body
            Statements;
        }

The part of the loop that contains the statements to be repeated is called the loop body.

包含要重复执行语句的部分称为循环体。

A one-time execution of a loop body is referred to as an iteration (or repetition) of the loop.

循环体的一次执行称为循环的一轮。

Each loop contains a loop-continuation-condition, a Boolean expression that controls the execution of the body.

循环还包括循环条件,它是控制循环体是否执行的逻辑表达式。

It is evaluated each time to determine if the loop body is executed.

每次进入循环体之前都要根据循环条件判断是否执行。

If its evaluation is true, the loop body is executed; if its evaluation is false, the entire loop terminates and the program control turns to the statement that follows the while loop.

如果满足循环条件,循环体就开始执行;如果不满足循环条件,整个循环终止并执行循环后续的语句。

The flowchart of the loop for displaying Welcome to Java! a hundred times is shown on the right side of this slide.

下面这两个流程图分别是循环语句和上面那个输出输出Welcome to Java!一百次的流程图。

The loop-continuation-condition is count < 100 and the loop body contains two statements.

从上图可以看出,循环条件是count < 100,循环体包含两条语句。

Loop Condition and Loop Body

循环条件和循环体

In this example, you know exactly how many times the loop body needs to be executed because the control variable count is used to count the number of iterations.

上面这个例子通过控制变量count计数来告诉我们这个循环体到底执行力多少次。

This type of loop is known as a counter-controlled loop.

这种循环称为计数控制循环。

The loop-continuation-condition must always appear inside the parentheses.

循环条件必须要写在小括号里面。

The braces enclosing the loop body can be omitted only if the loop body contains one or no statement.

如果循环体为空或只包含一条语句时,我们可以不写这一对中括号。

Trace while Loop

循迹while循环

int count=0;
        while (count<2){
            System.out.println("Welcome to Java!");
            count++;
        }

Let’s this time, assume that we want to print the Welcome to Java! two times on the console and trace the code to see how it works.

现在我们对一个while循环的程序进行控制台循迹测试,这个程序输出Welcome to Java!两遍。

int count=0;

First, the count variable is initialized to zero.

第一行,count这个变量初始化为0。

while (count<2){

The condition of “count is less than 2” is true.

第二行,判断循环条件,count<2成立,进入循环体。

System.out.println("Welcome to Java!");

So, the loop body is executed and it prints Welcome to Java!

第三行,循环体执行,打印出Welcome to Java!

count++;

Then increase the count variable by one and the count variable is 1 now.

第四行,变量count的值加1,变为1。

while (count<2){

The condition of “count is less than 2” is still true since the count variable is 1.

重新回到第二行,因为count=1,循环条件仍然成立,进入循环体。

System.out.println("Welcome to Java!");

So, the loop body is executed again and it prints Welcome to Java!

再次执行第三行,打印出Welcome to Java!

count++;

Then increase the count variable by one and the count variable is 2 now.

再次执行第四行,变量count的值加1,变为2。

while (count<2){

The condition of “count is less than 2” is false since the count variable is 2.

重新回到第二行,因为count=2,循环条件不成立成立。

So, it exits the loop and executes the statement after the loop.

所以循环结束,继续执行后续代码。至此,循迹结束。

Common Error

常见错误1

What will happen if the loop is mistakenly written as follows?

下面这段代码有什么问题?

int sum=0, i=1;
        while (i<10){
          sum=sum+1;
        }

This loop is infinite because i is always 1 and i < 10 will always be true.

上面这个是死循环因为变量i永远是1,循环条件i<10永远成立。

Make sure that the loop-continuation-condition eventually becomes false so that the loop will terminate.

我们必须要保证循环条件最后不成立,这样循环才能结束,后面的代码才能执行。

A common programming error involves infinite loops (the loop runs forever).

一个常见的编程错误就是死循环。

If your program takes an unusually long time to run and does not stop, it may have an infinite loop.

如果程序执行了很长时间一直不结束,那么很可能是有死循环。

If you are running the program from the command window, press CTRL+C to stop it.

如果在命令行里运行程序,可以用ctrl+c结束程序。

Common Error

常见错误2

How many times does the loop body execute?

在下面这段代码中,循环体执行了几次?

int count=0;
        while (count<=100){
            System.out.println("Welcome to Java!");
            count++;
        }

Programmers often make the mistake of executing a loop one more or less time.

一个常见的错误是循环执行多一次或是少一次。

This is commonly known as the off-by-one error.

这个错误也叫大小差一错误。

For example, the following loop displays Welcome to Java 101 times rather than 100 times.

比如说上面这个循环会打印Welcome to Java一共101次而不是100次,因为第一次进入循环体时count=0,也就是0到100共101次。

The error lies in the condition, which should be count < 100 rather than count <= 100.

这是一个逻辑错误,循环条件应该是count < 100。

Loop Design Strategies

循环设计方法

The key to designing a loop is to identify the code that needs to be repeated and write a condition for terminating the loop.

设计循环的关键是找到需要重复执行的代码作为循环体,还有退出循环的循环条件。

Writing a correct loop is not an easy task for novice programmers.

对于编程菜鸟来说写一个正确的循环语句也不简单。

Consider three steps when writing a loop.

设计循环的三步骤。

Step 1: Identify the statements that need to be repeated.

第一步:找出需要重复的语句。

Step 2: Wrap these statements in a loop as follows:

while (true) {
// Statements;
}

第二步:把这些语句像上面这段代码这样包括在while里面。

Step 3: Code the loop-continuation-condition and add appropriate statements for controlling the loop.

第三步:编写循环条件并添加合适的语句来控制循环,像下面这段代码。

while (loop-continuation-condition) {
// Statements;
// Additional statements for controlling the loop;
}

Controlling a Loop with User Confirmation or a Sentinel Value

用一个控制变量或是用户输入来控制循环

It is a common practice to use a sentinel value to terminate the input.

我们经常要用控制变量的值或用户输入来用户重新输入。

If you want the user to decide whether to continue, you can offer a user confirmation.

如果你想让用户决定循环是否重复执行,你可以做一个用户确认语句。

The template of the program can be coded as shown in this code followin:

一个让用户输入来控制循环执行的程序如下:

char continueLoop='Y';
        while (continueLoop=='Y'){
            System.out.println("hello");
            Scanner input=new Scanner(System.in);
            // Prompt the user for confirmation
            System.out.print("Enter Y to continue and N to quit: ");
            // get the first letter of the user input
            continueLoop=input.nextLine().charAt(0);

Another common technique for controlling a loop is to designate a special value when reading and processing a set of values.

另外一种控制循环的手段是在读取和处理一组数据时指定一个特殊值。

This special input value, known as a sentinel value, signifies the end of the input.

这样一个输入的数值叫做守护值,它标志着输入的结束。

A loop that uses a sentinel value to control its execution is called a sentinel-controlled loop.

一个由守护值决定执行的循环叫做守护控制循环。

Similarly, the loop in (c) is also wrong. (c) is equivalent to (d). Both are incorrect.

Note

注意

In the case of the do-while loop, the semicolon is needed to end the loop.

如下图这样,在do-while循环的while循环之后需要一个;

which Loop to Use?

循环使用的选择

The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms.

while, do-while, and for循环在表达上可以相互转化,就是说我们用这三种循环都可以。

For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b).

像上图这样,我们可以把while循环转换为for循环。

A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases.

除一些特殊情况之外,for循环也可以转换为while循环。
Use the one that is most intuitive and comfortable for you.

我们要在具体问题中使用不同循环。

In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times.

一般来说,一个for循环
A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0.
A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.

nested Loop

嵌套循环

Nested loops consist of an outer loop and one or more inner loops.

嵌套循环包括一个外部循环和n个内部循环。

Each time the outer loop is repeated, the inner loops are re-entered and started anew.

每当外层循环执行一次,内部循环就会重新进入执行。

break and continue

Two keywords, break and continue, can be used in loop statements to provide additional controls.

两个关键字可以用在循环中增加额外的控制。

Using break and continue can simplify programming in some cases.

在一些情况下,使用这些循环可以简化程序。
Overusing or improperly using them, however, can make programs difficult to read and debug.

但是用不好也会事与愿违。

You have used the keyword break in a switch statement.

我们在上一章switch语句中已经用过了break关键字。

You can also use break in a loop to immediately terminate the loop.

brrak关键字就是直接退出整个循环。

The program shown in this slide adds integers from 1 to 20 in this order to sum until sum is greater than or equal to 100.

上面这个程序意为

Without the if statement, the program calculates the sum of the numbers from 1 to 20.

However, with the if statement, the loop terminates when sum becomes greater than or equal to 100.

Continue

continue语句

You can also use the continue keyword in a loop.
When it is encountered, it ends the current iteration and program control goes to the end of the loop body.
In other words, continue breaks out of an iteration, while the break keyword breaks out of a loop.

也就是说continue关键字是跳过本次循环,break关键字是之间跳出全部循环了。

The program shown in this slide adds integers from 1 to 20 except 10 and 11 to sum.

上面这个程序计算1到20之和,但是10和11不算。

With the if statement in the program, the continue statement is executed when number becomes 10 or 11.

当x=10或x=11时,continue语句就会执行,跳过这次循环。

The continue statement ends the current iteration so that the rest of the statement in the loop body is not executed; therefore, number is not added to sum when it is 10 or 11.

就是说continue语句跳过这次循环,10和11不会加进去了。

note

注意

The continue statement is always inside a loop.

continue语句只能出现在循环体中。

In the while and do-while loops, the loop- continuation-condition is evaluated immediately after the continue statement.

在遇到语句之后,循环条件会立即判断。

In the for loop, the action-after-each-iteration is performed, then the loop-continuation-condition is evaluated immediately after the continue statement.

for循环中遇到continue语句时,每次迭代对于控制变量的改变会先执行一次,然后再判断循环条件。

The "for each" Loop

针对每个元素的循环

Java supports a convenient for loop, known as a foreach loop, which enables you to traverse the array sequentially without using an index variable.

Java提供一种“针对每一个元素”的循环,可以用它顺序遍历数组,不用加下标了。

For example, the code shown in this slide displays all the elements in the array myList: You can read the code as “for each element e in myList, do the following.”

下面这个例子就是

int[] arr = new int[]{1,2,3,4,5};
        for (int e:arr){
            System.out.println(e);
        }

Note that the variable, e, must be declared as the same type as the elements in myList.

也就是针对整型变量e,打印整个数组。

You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.

但是如果用不同的顺序遍历数组,那还是要用下标。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只萌新兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值