java学习笔记(七)-控制流语句-循环

本文详细介绍了Java中的循环控制语句,包括while、do-while、for循环的语法规则和使用示例,以及break和continue语句在循环中的应用,还有return声明的作用。
摘要由CSDN通过智能技术生成

java学习笔记(六)-控制流语句-循环


顺序结构的程序语句只能被执行一次。如果您想要同样的操作执行多次,,就需要使用循环结构。

Java中有三种主要的循环结构:

  • while 循环
  • do…while 循环
  • for 循环

在Java5中引入了一种主要用于数组的增强型for循环。

while和do-while语句

语法规则

while语句在特定条件为时连续执行语句块true。它的语法可以表示为:

while (expression) {
     statement(s)
}

while语句对**表达式(expression)求值,该表达式(expression)**必须返回一个boolean值。如果表达式的计算结果为true,该while语句执行语句在(多个)while块。该while语句继续测试表达式并执行其块,直到表达式的值为false

Example

class WhileDemo {
    public static void main(String[] args){
        int count = 1;
        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}

使用该while语句打印从1到10的值

您可以使用以下while语句实现无限循环:

whiletrue{ 
    //您的代码在此处
}

Java编程语言还提供了一条do-while语句,

do…while 循环

语法规则

对于 while 语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次。

do {
     statement(s)
} while (expression);

Example

class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

for语句

语法规则

for语句提供了一种紧凑的方法来迭代一系列值。

for循环执行的次数是在执行前就确定的。语法格式如下:

for (initialization; termination;increment) {
    statement(s)
}

使用此版本的for语句时,请记住:

  • 初始化表达初始化回路; 当循环开始时,它执行一次。
  • 终止表达式的计算结果为时false,循环终止。
  • 增量通过循环每次迭代之后表达被调用; 对于该表达式,增加减少值是完全可以接受的。

Example

class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}

该程序的输出为:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

请注意,代码是如何在初始化表达式中声明变量的。此变量的范围从其声明扩展到该for语句所控制的块的末尾,因此也可以在终止和增量表达式中使用它。如果for循环外不需要控制语句的变量,则最好在初始化表达式中声明该变量。名称ijk通常用于控制for循环。在初始化表达式中声明它们会限制它们的寿命并减少错误。

for循环的三个表达式是可选的。可以如下创建无限循环:

// infinite loop
for ( ; ; ) {
    
    // your code goes here
}

for语句还具有另一种设计用于通过Collections数组进行迭代的形式。 该形式有时被称为for语句的增强功能,可用于使循环更紧凑和易于阅读。为了演示,考虑下面的数组,其中包含数字1到10:

class EnhancedForDemo {
    public static void main(String[] args){
         int[] numbers = 
             {1,2,3,4,5,6,7,8,9,10};
         for (int item : numbers) {
             System.out.println("Count is: " + item);
         }
    }
}

在此示例中,变量item保存了numbers数组中的当前值。该程序的输出与以前相同:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

我们建议for尽可能使用这种形式的语句,而不是一般形式。

break语句

break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块。break 跳出最里层的循环,并且继续执行该循环下面的语句。

语法

break 的用法很简单,就是循环结构中的一条语句:

Example
class BreakDemo {
    public static void main(String[] args) {

        int[] arrayOfInts = { 32, 87, 3, 589,12, 1076, 2000,8, 622, 127 };
        int searchfor = 12;
        int i;
        boolean foundIt = false;

        for (i = 0; i < arrayOfInts.length; i++) {
            if (arrayOfInts[i] == searchfor) {
                foundIt = true;
                break;
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at index " + i);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

运行结果如下:

Found 12 at index 4

continue

  • continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。

  • 在 for 循环中,continue 语句使程序立即跳转到更新语句。

  • 在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。

语法

continue 就是循环体中一条简单的语句:

class ContinueDemo {
    public static void main(String[] args) {

        String searchMe = "peter piper picked a " + "peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            // interested only in p's
            if (searchMe.charAt(i) != 'p')
                continue;

            // process p's
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

运行结果如下:

Found 9 p's in the string.

若要更清楚地看到此效果,请尝试删除该continue语句并重新编译。当您再次运行该程序时,计数将是错误的,表示它找到的是35 p而不是9。

带标签的continue语句跳过用给定标签标记的外部循环的当前迭代。

class ContinueWithLabelDemo {
    public static void main(String[] args) {

        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() - 
                  substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

Here is the output from this program.

class ContinueWithLabelDemo {
    public static void main(String[] args) {

        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() - 
                  substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

运行结果如下:

Found it

return声明

return语句有两种形式:一种返回值,另一种不返回值。要返回值,只需将值(或计算值的表达式)放在return关键字之后。返回值的数据类型必须与方法声明的返回值的类型匹配。声明方法时void,使用的形式return不返回值。

控制流语句摘要

if-then语句是所有控制流语句中最基本的。它告诉您的程序仅在特定测试的结果为时才执行代码的特定部分trueif-then-else当“ if”子句的计算结果为时,该语句提供了执行的辅助路径false。与if-then和不同if-then-else,该switch语句允许任何数量的可能执行路径。在whiledo-while而特定的条件语句不断执行的语句块true。之间的差do-whilewhiledo-while在循环的而不是顶部的底部评估其表达。因此,该do块内的语句始终至少执行一次。的for语句提供了一种紧凑的方法来迭代一系列值。它有两种形式,其中一种是为遍历集合和数组而设计的。

是所有控制流语句中最基本的。它告诉您的程序仅在特定测试的结果为时才执行代码的特定部分trueif-then-else当“ if”子句的计算结果为时,该语句提供了执行的辅助路径false。与if-then和不同if-then-else,该switch语句允许任何数量的可能执行路径。在whiledo-while而特定的条件语句不断执行的语句块true。之间的差do-whilewhiledo-while在循环的而不是顶部的底部评估其表达。因此,该do块内的语句始终至少执行一次。的for语句提供了一种紧凑的方法来迭代一系列值。它有两种形式,其中一种是为遍历集合和数组而设计的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值