for循环结构
for (初始化语句;条件判断语句;条件控制语句) {
循环体语句;
}
- 变量的范围属于当前的大括号。
for循环练习-统计数字个数
需求:键盘录入两个数字,表示一个范围。统计这个范围中,既能被3整除,又能被5整除数字有多少个?
package come.itheima.Test;
import java.util.Scanner;
public class Test16 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数字表示范围的开始");
int start = sc.nextInt();
System.out.println("请输入第二个数字表示范围的结束");
int end = sc.nextInt();
int count = 0;
for(int i = start; i <= end; i++){
if(i % 3 ==0 && i %5 == 0) {
count++;
}
}
System.out.println(count);
}
}
while循环结构
初始化语句;
while(条件判断语句){
循环体;
条件控制语句;
}
while循环练习-回文数
需求:键盘录入一个正整数,判断是否为回文数。回文数是指从左向右和从右向左读都一样,例如121,1221,12321,11。
法一:
package come.itheima.Test;
import java.util.Scanner;
public class Test18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请录入一个正整数");
int x = sc.nextInt();
int temp = x;
int number = 0;
while (x != 0) {
int ge = x % 10;
x = x / 10;
number = number * 10 + ge;
}
System.out.println(number == temp);
}
}
法二:
package come.itheima.Test;
import java.util.Scanner;
public class Test18_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请录入一个正整数");
int x = sc.nextInt();
int i = 1;
int number = 0;
while(x/i != 0 ) {
int g = x / i % 10;
number = number * 10 + g;
i = i *10;
}
System.out.println(number == x);
}
}
do…while循环结构
初始化语句;
do{
循环体;
条件控制语句;
}while(条件判断语句);
- 特点:
先执行,再判断。
三种格式的区别
- for和while循环,是先判断,再执行。
- do…while是先执行,再判断。
- 当知道循环次数或者循环范围的时候,用for循环。
- 当不知道循环次数,也不知道循环范围,但是知道循环的结束条件时,用while循环。
引用
https://www.bilibili.com/video/BV17F411T7Ao?spm_id_from=333.999.0.0
以上内容仅作为个人学习笔记,无商业行为。