-
while循环
-
do...while循环
-
for循环
-
Java5中引用了一种主要用于数组的增强型for循环
while循环
while(布尔表达式){ //循环内容 }
-
只要布尔表达式为true,循环就会一直执行
-
大多数情况都要让循环停止下来,需要一个让表达式失效的方式来结束循环
-
少部分情况需要一直循环,比如服务器请求响应监听等
-
循环条件一直为true就会造成无限循环,正常情况下的业务变成应该尽量避免死循环
输出1~100
public class WhileDemo {
public static void main(String[] args) {
int i = 0;
while(i<100){
i++;
System.out.println(i);
}
}
}
死循环
-
大多情况下尽量避免死循环,不然就GG
public class WhileDemo {
public static void main(String[] args) {
while(true){
//等待客户端连接
//闹钟、定时检查
//。。。。。。。。
}
}
}
计算1+2+3+...+100
public class WhileDemo02 {
public static void main(String[] args) {
int i = 0;
int sum = 0;
while(i<=100){
sum = sum + i;
i++;
}
System.out.println(sum);
}
}
do...while
-
对于while而言,不满足条件则不能进入循环
-
do...while即使不满足条件也至少执行一次
do{
//代码
}while(布尔表达式);
while和do...while的区别
-
while先判断后执行;do...while先执行后判断
-
do...while保证循环至少执行一次
public class DowhileDemo01 {
public static void main(String[] args) {
int a = 0;
while(a<0){
System.out.println(a);
a++;
}//没有输出
System.out.println("=======================");
do {
System.out.println(a);
a++;
}while (a<0);//输出0
}
}
For循环
-
for循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构
-
关于for循环的几点说明
-
最先执行初始化步骤,可以声明一种类型,可初始化一个或多个循环控制变量,也可以是空语句
-
然后检测布尔表达式的值,如果为true,循环执行,如果为false,循环终止
-
执行一次循环后,更新循环控制变量
-
再次检查布尔表达式,循环执行上面的过程
-
for(初始化;布尔表达式;更新){
//代码语句
}
//for死循环
for( ; ; ){
}
计算0到100之间的奇数和和偶数和
public class ForDemo02 {
public static void main(String[] args) {
int oddSum = 0;//奇数和
int evenSum = 0;//偶数和
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0){
evenSum += i;
}else {
oddSum += i;
}
}
System.out.println("奇数和:"+oddSum);
System.out.println("偶数和:"+evenSum);
}
}
用while或for循环输出1~1000之间能被5整除的数,并且每行输出3个
while
public class ForDemo03 {
public static void main(String[] args) {
int i = 1;
while (i <= 1000) { //i<=1000执行循环
if(i % 5 == 0) { //如果i能被5整除,执行if语句
System.out.print(i + "\t"); //输出i;***不能使用println而是使用print***
}
if (i % (5*3) == 0){ //每行输出3个,如果i/15的时候等于0,则执行换行
System.out.println(); //两种方法都是换行
//System.out.println("\n");
}
i++;
}
/*
println和print的差别
print:输出完不会换行
println:输出玩会换行
*/
}
}
for
public class ForDemo04 {
public static void main(String[] args) {
for (int i = 1;i <= 1000;i++){
if (i % 5 == 0){
System.out.print(i + "\t");
}
if (i % (5*3) == 0){
System.out.println();
}
}
}
}
九九乘法表
public class ForDemo05 {
public static void main(String[] args) {
//1.打印第一列for(int i=1;i<=9;i++)
//2.把固定的1用j循环抱起来for(int j=1;j<=9;j++)
//3.去掉重复项,把i<=9改为i<=j
//4.调整样式"\t"、"\n"
for (int j = 1; j <= 9; j++) {
for (int i = 1; i <= j; i++) {
System.out.print(j + "*" + i + "=" + (j*i) + "\t");
}
System.out.println();
}
}
}
增强for循环
-
jdk5引入的用于数组或集合的增强型for循环
for(声明语句:表达式)
{
//代码
}
public class ForDemo06 {
public static void main(String[] args) {
int[] numbers = {10,20,30,40,50};
//定义了一个数组
for(int i = 0;i < 5;i++){
System.out.println(numbers[i]);
}
System.out.println("===========================");
//遍历数组的元素
for (int x:numbers){
System.out.println(x);
}
}
}