#JAVA# 学习笔记 循环语句while,do-while,for

1. The while and do-while Statements

跟C也是一样的,写法不同,超过一次loop的操作一样。唯一不同是while会先判断,do-while一定会先做action,然后再判断。

//sudo code for while 
while (true){
    actions // your code goes here
}
//sudo code for do-while
do {
     statement(s)
} while (expression);
//in
class WhileDemo {
    public static void main(String[] args) {
        int count = 0;
        while (count<11){
            System.out.println(count);
            count++;
        }
        System.out.println("loop is ended");
    }
}

//out
0
1
2
3
4
5
6
7
8
9
10
loop is ended
//in 
class doWhileDemo {
    public static void main(String[] args) {
        int count =0;
        do{
            System.out.println(count);
            count++;
        }while (count<11);
        System.out.println("do-while loop is over");
    }
}

//out 
0
1
2
3
4
5
6
7
8
9
10
do-while loop is over

1.1 不同点

do-while 会先做一次action,然后再去判断;while是先判断,再去做action

//In
class WhileDemo {
    public static void main(String[] args) {
        int count = 0;
        while (count>11){
            System.out.println(count);
            count++;
        }
        System.out.println("the loop is ended");
    }
}

//Out 
the loop is ended
//In
class doWhileDemo {
    public static void main(String[] args) {
        int count =0;
        do{
            System.out.println(count);
            count++;
        }while (count>11);
        System.out.println("do-while loop is over");
    }
}

//Out
0
do-while loop is over

2. For循环

For的写法也是跟C一样,无限流一般用来做自动化测试跑一段时间,出错break就好。

//sudo code
for(初始化;条件;增量){
    actions; }
// infinite loop
for ( ; ; ) {
    
    // your code goes here
}
//In
class forDemo {
    public static void main(String[] args) {
        for(int count = 0; count<5;count++){
            System.out.println("count is " + count);
        }
        System.out.println("for loop is ended");
    }
}

//out 
count is 0
count is 1
count is 2
count is 3
count is 4
for loop is ended


2018.6.21 代码来自java8官方文档,这里用作学习调试

你可能感兴趣的:(#JAVA# 学习笔记 循环语句while,do-while,for)