定义
- while(循环条件){
循环操作 // 先判断,再执行
}
- 程序调试
-- 设置断点
-- 单行运行
-- 观察变量
- do{
循环操作 //x先执行,后判断
}while(循环条件);
- for(参数初始化;条件判断;更新循环变量)
{
循环操作
}
- break:改变程序控制流(中断,跳出整个循环)
- continue:跳出本次循环
例题
int a=1;
int total=0;
while(i<=100)
{
if(a%2 == 0)
{
total=total+a;
}
a++;
}
System.out.priintln(total);
- 实现整数反转 用户输入任意一个数字比如12345,程序输出54321
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个数");
int num = scanner.nextInt();
while(num>0)
{
System.out.print(num % 10);
num = num / 10;
}
public class whileDemo2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入学生姓名");
String name = scanner.next();
int score = 0;
int total = 0;
for(int i = 1; i <= 5; i++)
{
System.out.println("请输入"+i+"成绩");
score = scanner.nextInt();
total = total + score;
}
System.out.println(name+"的平均成绩是"+total/5);
}
}
public class whileDemo2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入学生姓名");
String name = scanner.next();
int score = 0;
int total = 0;
boolean error = false;
for(int i = 1; i <= 5; i++)
{
System.out.println("请输入"+i+"成绩");
score = scanner.nextInt();
if(score<0 || score>100)
{
error = true;
break;
}
total = total + score;
}
if(error == false)
{
System.out.println(name+"的平均成绩是"+total/5);
}
else
{
System.out.println("录入有误");
}
}
}
public static void main(String[] args) {
int count = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入班级总人数");
int personCount = scanner.nextInt();
for(int i = 1; i <= personCount; i++)
{
System.out.println("请输入第" + i + "次成绩");
int score = scanner.nextInt();
if(score < 80)
{
continue;
}
count++;//累加成绩大于等于80的次数
}
System.out.println("80分以上学生人数为" + count);
}
}