正常循环
package com.flower.struct;
public class WhileDemo01 {
static void main(String[] args) {
// 输出1~100
int i = 0;
while (i < 100) {
i++;
System.out.println(i);
}
}
}
死循环
package com.flower.struct;
public class WhileDemo02 {
static void main(String[] args) {
// 死循环,业务中应尽量避免死循环。会影响程序性能或者造成程序卡死崩溃!
while (true) {
// 等待客户端连接
// 定时检查
//......
}
}
}
计算1-100的和
package com.flower.struct;
public class WhileDemo03 {
static void main(String[] args) {
// 计算1+2+3+......+100=?
int count = 0;
int sum = 0;
while (count <= 100) {
sum = sum + count;
count++;
}
System.out.println(sum);
}
}
do while循环
package com.flower.struct;
public class DoWhileDemo01 {
static void main(String[] args) {
int count = 0;
int sum = 0;
// 做循环......直到......
// 至少执行一次
do {
sum = sum + count;
count++;
} while (count <= 100);
System.out.println(sum);
}
}
While 和 do-While 的区别:
- while 先判断后执行。dowhile 是先执行后判断!
- Do...while 总是保证循环体会被至少执行一次!这是他们的主要差别。
package com.flower.struct;
public class DoWhileDemo02 {
static void main(String[] args) {
int a = 0;
//while循环与do while循环的对比
// 无输出,条件判断不成功,没有做循环
while (a < 0) {
System.out.println(a);
a++;
}
System.out.println("==============================");
// 输出0,做了一次循环
do {
System.out.println(a);
a++;
} while (a < 0);
}
}