Java 入门之循环结构

for 循环

格式

for (初始化语句 ; 循环的条件表达式 ; 初始化变量的自增 ) {

  循环体语句;

}

//99乘法表的打印
class Test
{
    public static void main(String[] args) 
    {
        for (int i=1; i<=9;i++)
        {
            for (int j=1;j<=i;j++)
            {
                System.out.print(i+"*"+j+"="+i*j+"	");
            }
            System.out.println();
        }
    }
}
99乘法表之for循环嵌套
class Test2
{
    public static void main(String[] args) 
    {
        for (int i=1;i<=5;i++)
        {
            for (int j=1;j<=5-i;j++)
            {
                System.out.print(" ");
            }
            for (int k=1;k<=2*i-1;k++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
打印*三角形

while 语句

格式:

  初始化语句

  while(条件表达式) {

    循环体语句;

    初始化变量的自增;

}

注意事项:

  1、条件表达式必须为boolean类型

  2、初始化变量的自增,不要忘记

 

class Test3 {
    public static void main(String[] args) {
        int i = 1;//初始化语句
        while(i <= 5) {//判断循环条件
            //循环体语句
            System.out.println("Hello World!");
            i++;//初始化变量的自增
        }
    }
}

 

do while语句

格式:

  初始化语句;

  do {

     循环体语句;

    初始化变量的自增;

} while (循环条件表达式);

 

注意事项:

 

  1、循环条件表达式必须是boolean类型

 

  2while循环条件后面,要有一个分号

 

class Test4 {
    public static void main(String[] args) {
        //初始化语句
        int i = 1;
        do {
            System.out.println("Hello World!");
            i++;
        } while (i <= 5);
    }
}

三种循环结构的比较

1、dowhile语句和其他两种语句的区别:

  dowhile语句至少可以执行一次,另外两种有可能一次都执行不了

2、while语句和for的区别:

  (1)代码层面:while语句声明的初始化变量,在while结束之后,还能继续使用;for中声明的初始化变量,在for结束之后,就无法使用了。

  (2)设计层面:while语句一般用于描述相对模糊的范围,其他的条件;for用于描述相对准确,知道循环次数的循环

 死循环

1、死循环:无限循环。循环永远都不停止。

2、格式:

(1)for语句的死循环:

    for ( ; ; ) {

循环体语句;

}

(2)while语句的死循环:【常用】

    while (true) {

      循环体语句;

}

(3)死循环的作用:

  1、在格式上使用了死循环,但是在循环体中,可能出现了需要循环结束的情况,准备了一些跳出、终止循环的跳转语句。

  2、在服务器的设计中,希望服务器永远给我们服务下去,所以需要使用死循环。

 

跳转语句

 

1、跳转语句:在循环的循环体语句中,结束循环,控制循环,使用的语句。

 

2、continue语句:

 

  结束本次循环,继续下次循环

 

3、break语句:

 

  结束当前层次的循环

 

4、return语句:

 

  结束当前的方法

 

 

 

 

原文地址:https://www.cnblogs.com/xfdhh/p/11147421.html