Java的循环结构

158 阅读3分钟

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

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

while 循环

while是最基本的循环,只要布尔表达式为 true,循环就会一直执行下去。如果布尔表达式为 false,则不再进入循环。其结构为:

while( 布尔表达式 ) {
  //循环内容
}

while 循环使用实例:

public class Test {
    public static void main(String[] args) {
        int x = 10;
        while( x < 15 ) {
            System.out.print("value of x : " + x );
            x++;
            System.out.print("\n");
        }
    }
}

// 运行结果如下:
// value of x : 10
// value of x : 11
// value of x : 12
// value of x : 13
// value of x : 14

do…while 循环

对于 while 语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次,此时可以运用do…while 循环。因为do…while 循环布尔表达式在循环体的后面,所以语句块在检测布尔表达式之前已经执行了。 如果布尔表达式的值为 true,则语句块一直执行,直到布尔表达式的值为 false。其结构为:

do {
       //代码语句
}while(布尔表达式);

do…while 循环使用实例:

public class Test {
    public static void main(String[] args) {
        int x = 22;

        do{
            System.out.print("value of x : " + x );
            x++;
            System.out.print("\n");
        }while( x < 20 );
    }
}

// 运行结果如下:
// value of x : 22

for循环

虽然所有循环结构都可以用 while 或者 do...while表示,但 Java 提供了另一种语句 —— for 循环,使一些循环结构变得更加简单。for循环执行的次数是在执行前就确定的。语法格式如下:

for(初始化; 布尔表达式; 更新) {
    //代码语句
}

关于 for 循环执行说明:

  • 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
  • 然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
  • 执行一次循环后,更新循环控制变量。
  • 再次检测布尔表达式。循环执行上面的过程。

for 循环使用实例:

public class Test {
    public static void main(String[] args) {
        for(int x = 10; x < 15; x = x+1) {
            System.out.print("value of x : " + x );
            System.out.print("\n");
        }
    }
}

// 运行结果如下:
// value of x : 10
// value of x : 11
// value of x : 12
// value of x : 13
// value of x : 14

Java 增强 for 循环

Java5 引入了一种主要用于数组的增强型 for 循环。Java 增强 for 循环语法格式如下:

for(声明语句 : 表达式)
{
   //代码句子
}

增强 for 循环执行说明:

  • 声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
  • 表达式:表达式是要访问的数组名,或者是返回值为数组的方法。

增强 for 循环使用实例:

public class Test {
   public static void main(String[] args){
      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names ={"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}
// 运行结果如下:
// 10,20,30,40,50,
// James,Larry,Tom,Lacy,

break 关键字

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

break 关键字使用实例:

public class Test {
    public static void main(String[] args) {
        int[] intary = { 99,12,22,34,45,67,5678,8990 };
        int no = 5678;
        int i = 0;
        boolean found = false;
        // 循环数组元素
        for ( ; i < intary.length; i++) {
            // 找到指定元素后跳出循环
            if (intary[i] == no) {
                found = true;
                break;
            }
        }
        // 找到元素,输出元素在数组中的索引
        if (found) {
            System.out.println(no + " 元素的索引位置在: " + i);
        }
        // 未找到索引
        else {
            System.out.println(no + " 元素不在数组中");
        }
    }
}

// 运行结果如下:
// 5678 元素的索引位置在: 6

continue 关键字

continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。在 for 循环中,continue 语句使程序立即跳转到更新语句。在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。

continue 关键字使用实例:

public class Test {
    public static void main(String[] args) {
        // 创建可变字符串 StringBuffer 对象
        StringBuffer searchstr = new StringBuffer("hello how are you. ");
        // 获取字符串长度
        int length = searchstr.length();
        // 计数
        int count = 0;
        // 循环字符串字符
        for (int i = 0; i < length; i++) {
            // 如果字符不是'h',结束本次循环,进入下次循环
            if (searchstr.charAt(i) != 'h'){
                continue;
            }
            // 是'h'字符,计数加1
            count++;
            // 设置字符串该索引位置的字符为'h'
            searchstr.setCharAt(i, 'h');
        }
        // 输出'h'字符个数
        System.out.println("发现 " + count
                + " 个 h 字符");
        // 输出字符串内容
        System.out.println(searchstr);
    }
}

// 运行结果如下:
// 发现 2 个 h 字符
// hello how are you. 

嵌套循环实例分析

  • 打印三角形

首先,确定我们的输出结果是:

f44a8db53ea3d09955d3aa5f013b5e7a.jpg

1、首先分析图形的结构。我们可以看到,图形共5行,那么,我们是否可以建立一个for循环语句,使其控制在5行?答案是肯定的:

// 这样,我们就建立了一个循环5次的for循环代码块,为最外圈的循环
for(int i = 1 ;i <= 5 ;i++ ){

}

2、然后,分析图形是怎样构成的,我们可以把图形拆分为这样三个三角形:

e66ee03bb2a9b62f47a262ecbdd117c2.jpg

3、建立1号空白三角形。可以看,第一行是输出4个空格,第二行输出3个空格,第三行输出2个,第四行输出1个,第五行没有。从这个规律可以看出,是依次递减的规律,那么如何实现呢?我们可以想象从1到5,中间有四个数字;从2到5中间有3个数字,从3到5……,是不是可以利用这个原理呢?答案是当然的。那么如何实现?请看代码:

// 一个循环5次的for循环代码块,为最外圈的循环
for(int i = 1;i<=5 ;i++) {
   // 建立1号图形
   for(int j = 5; j >= i ; j--){
       System.out.print(" ");
   }
   // 换行
   System.out.println();
}

代码解析:

  1. 第一个 for 语句就是刚才定义的五次循环语句。
  2. 第二个 for 循环,首先定义一个 int 类型的 j 变量,给 j 赋值为5;然后我们想,既然要缩短距离,那么每次循环 j 就减1,那么刚好符合我们的要求:

第一次大循环 i=1,j=5,所以符合 j>=i 的条件,然后输出一个空格,然后 j-1,现在 j 的值为4符合 j>=i,再输出一个空格……一直到 j=0,j>=i 不符合,跳出内循环; 现在到System.out.println(); 换行; 现在回到外循环 i++,i 变成2,符合 i<=5,进入内循环。定义 j=5, j>=i 符合,输出一个空格,j-1,j 现在为4 ,j>=i 符合,输出一个空额,j-1……一直到 j=1,j>=i 不成立,跳出内训还,然后换行; 然后i+1 然后再进入内循环……如此循环下去,形成了一个四行的倒三角,1号图案形成。

4、建立2号图形,和1号图形原理完全相同,不过正好相反:

// 一个循环5次的for循环代码块,为最外圈的循环
for(int i = 1;i<=5 ;i++) {
    // 建立1号图形
    for(int j = 5; j >= i ; j--) {
          System.out.print(" ");
    }
    // 建立2号图形
    for(int j = 1; j <= i; j++) {
         System.out.print("*");
     }
     // 换行
     System.out.println();
}

5、建立3号图形,3号图形没有在第一行输出,所以要在第一次大循环中掐断它,让它在第二次大循环中输出:

// 一个循环5次的for循环代码块,为最外圈的循环
for(int i = 1;i<=5 ;i++) {
    // 建立1号图形
    for(int j = 5; j >= i ; j--) {
         System.out.print(" ");
    }
    // 建立2号图形
    for(int j = 1; j <= i; j++) {
         System.out.print("*");
     }
    // 建立3号图形
    for(int j = 1; j < i; j++) {
         System.out.print("*");
    }
     // 换行
     System.out.println();
}

运行结果如下:

     *
    ***
   *****
  *******
 *********

嵌套循环实例

  • 打印倒三角形:
public class Test {
    public static void main(String[] args) {
        // 一个循环5次的for循环代码块,为最外圈的循环
        for (int m = 0; m < 5; m++) {
            // 输出空格,逐行增加
            for (int n = 0; n <= m; n++) {
                System.out.print(" ");
            }
            // 输出 * 号,每行减少2颗
            for (int x = 0; x < 7 + 2 - (m * 2); x++) {
                System.out.print("*");
            }
            // 换行
            System.out.println();
        }
    }
}

运行结果如下:

 *********
  *******
   *****
    ***
     *
  • 打印矩形:
public class Test {
    public static void main(String[] args) {
        //外层循环 每次输出一行开头的第一颗*
        for (int i = 1; i <= 5; i++) {
            System.out.print("*");
            //内层循环 每次在同一行中输出一个*
            for (int j = 1; j <= 5; j++) {
                System.out.print("*");
            }
            //输出换行
            System.out.println();
        }
    }
}

运行结果如下:

******
******
******
******
******
  • 打印平行四边形:
public class Test {
    public static void main(String[] args) {
        //外层循环 控制打出*的行数
        for (int i = 1; i <=5; i++) {
            //填充开头空格 j每次从1开始,随着i值增加。打印空格逐渐减少
            for (int j = 1; j <= 5 - i; j++) {
                System.out.print(" ");
            }
            //内层循环 每次打印一个* 控制每行有几个*
            for (int k = 1; k <= 5; k++) {
                System.out.print("*");
            }
            //输出换行
            System.out.println();
        }
    }
}

运行结果如下:

    *****
   *****
  *****
 *****
*****
  • 打印菱形:
public class Test {
    public static void main(String[] args) {
        // 输出 8 行的菱形
        print(8); 
    }

    // 静态方法,输出菱形
    public static void print(int size) {
        if (size % 2 == 0) {
            // 计算菱形大小,输出*的总行数
            size++;
        }
        // 外层循环,负责菱形上部分,比下半部分多循环一次
        for (int i = 0; i < size / 2 + 1; i++) {
            // 输出左上角位置的空白,每行减少1
            for (int j = size / 2 + 1; j > i + 1; j--) {
                System.out.print(" ");
            }
            // 输出菱形上半部*号,每行输出的*号增加2个
            for (int j = 0; j < 2 * i + 1; j++) {
                System.out.print("*");
            }
            // 换行
            System.out.println();
        }
        // 外层循环,负责菱形下部分,比上半部分少执行一次
        for (int i = size / 2 + 1; i < size; i++) {
            // 输出菱形左下角的空白,每行增加1
            for (int j = 0; j < i - size / 2; j++) {
                System.out.print(" ");
            }
            // 输出菱形下半部*号,每行输出的*号减少2个
            for (int j = 0; j < 2 * size - 1 - 2 * i; j++) {
                System.out.print("*"); // 输出菱形下半部边缘
            }
            // 换行
            System.out.println();
        }
    }
}

运行结果如下:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
  • 九九乘法表
public class Test {
    public static void main(String[] args) {
        // 一个循环9次的for循环代码块,为最外圈的循环,打印9行
        for (int i = 1; i <= 9; i++) {
            // 打印乘法口诀数列
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "x" + i + "=" + i*j + "\t");
            }
            //换行
            System.out.println();
        }
    }
}

运行结果如下:

1x1=1	
1x2=2	2x2=4	
1x3=3	2x3=6	3x3=9	
1x4=4	2x4=8	3x4=12	4x4=16	
1x5=5	2x5=10	3x5=15	4x5=20	5x5=25	
1x6=6	2x6=12	3x6=18	4x6=24	5x6=30	6x6=36	
1x7=7	2x7=14	3x7=21	4x7=28	5x7=35	6x7=42	7x7=49	
1x8=8	2x8=16	3x8=24	4x8=32	5x8=40	6x8=48	7x8=56	8x8=64	
1x9=9	2x9=18	3x9=27	4x9=36	5x9=45	6x9=54	7x9=63	8x9=72	9x9=81	
  • 反向九九乘法表
public class Test {
    public static void main(String[] args) {
        // 一个循环9次的for循环代码块,为最外圈的循环,打印9行
        for (int i = 9; i >= 1; i--) {
            // 打印乘法口诀数列
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "x" + i + "=" + i*j + "\t");
            }
            //换行
            System.out.println();
        }
    }
}

运行结果如下:

1x9=9	2x9=18	3x9=27	4x9=36	5x9=45	6x9=54	7x9=63	8x9=72	9x9=81	
1x8=8	2x8=16	3x8=24	4x8=32	5x8=40	6x8=48	7x8=56	8x8=64	
1x7=7	2x7=14	3x7=21	4x7=28	5x7=35	6x7=42	7x7=49	
1x6=6	2x6=12	3x6=18	4x6=24	5x6=30	6x6=36	
1x5=5	2x5=10	3x5=15	4x5=20	5x5=25	
1x4=4	2x4=8	3x4=12	4x4=16	
1x3=3	2x3=6	3x3=9	
1x2=2	2x2=4	
1x1=1