在JAVA程序中有一些程序段需要重复运行多次,这些程序段称为循环结构程序。JAVA语言提供了三种循环语句,包括for循环、while循环、do-while循环。
1.for循环
(1)结构
for(循环变量初始化;循环条件;循环变量迭代){
循环体;
}
循环条件为布尔表达式,为true执行循环体,为false结束循环。 先执行循环变量初始化,再执行循环条件,若为true,进而执行循环体(可以为一条语句也可以是多条语句的组合),最后执行循环变量迭代,然后继续执行循环条件,若为true则继续上述行为,若为false则 结束循环。
(2)示例
输出1+2+...+100的结果
public class LeiJia{
public static void main(String[] args) {
int num = 0;
for(int i = 1;i <= 100;i++){
num = num + i;
}
System.out.println(num);
}
}
2.while循环
(1)结构
循环变量初始化;
while(循环条件){
循环体;
循环变量迭代;
}
先执行循环变量初始化,再执行循环条件,若为true,进而执行循环体,最后执行循环变量迭代,然后继续执行循环条件,若为true则继续上述行为,若为false则结束循环。
(2)示例
输出1-n中各个位数之和为13的整数的个数(n<10000)
import java.util.Scanner;
public class l {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
int i = 1;
while (i <= n) {
int a = i % 10; //个位
int b = (i / 10) %10; //十位
int c = ( i /100) % 10; //百位
int d = i /1000; //千位
int e = a + b + c + d ;
if(e == 13){
count ++;
}
i++;
}
System.out.println(count);
}
}
3.do-while
(1)结构
循环变量初始化; do{
循环体;
循环变量的迭代;
}while(循环条件)
先执行循环变量初始化,然后执行循环体,再循环变量的迭代,最后执行循环条件,若为true,继续执行循环体,然后循环变量迭代,再执行循环条件,若为true则继续上述行为,若为false则结束循环。
(2)示例
输出1-n中各个位数之和为13的整数的个数(n<10000)
import Java.util.Scanner;
public class T {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
int i = 1;
do {
int a = i % 10; //个位
int b = (i / 10) %10; //十位
int c = ( i /100) % 10; //百位
int d = i /1000; //千位
int e = a + b + c + d ;
if(e == 13){
count ++;
}
i++;
} while (i <= n);
System.out.println(count);
}
}