@TOC
while 循环
使用方法:先判断,在执行;当条件表达式成立时,则执行循环体,然后在进行判断,如果条件不成立时,有可能不执行。一般用于循环次数不确定的循环。
代码实例:
public class testController {
public static void main(String[] args) throws Exception {
int x = 1; //定义变量x,初始值为1
while (x<= 4){ //x<=4,循环条件
System.out.println("x="+x); //条件成立,打印x的值
x++; //x进行自增
}
}
}
打印结果:
在这里插入图片描述
do....while 循环
使用方法:先执行,后判断;一般用于循环次数不确定的循环,与while循环不同的是先执行后判断,至少会执行一次。
package com.okq.controller.test;
public class testController {
public static void main(String[] args) throws Exception {
int x = 1; //定义变量x,初始值为1
do{
System.out.println("x="+x); //条件成立,打印x的值
x++; //x进行自增
} while (x<=4);
}
}
在这里插入图片描述
for 循环(已知循环次数)
使用方法:先判断,在执行;如果循环次数确定,那么一般用for循环
package com.okq.controller.test;
public class testController {
public static void main(String[] args) throws Exception {
int sum = 0 ; //定义变量sum,用于记住累加的和
for (int i = 0; i <=5 ; i++) {//i的值会在1-4之间变化
sum += i; //实现sum与i的累加
System.out.println("sum="+sum); //循环输出累加结果
}
}
}
在这里插入图片描述
网友评论