while循环
while(循环条件){
循环操作
}
int i = 1;
while(i <= 100){
System.out.println("好好学习,天天向上!");
i++;
}
示例
import java.util.*;
/**
* @Author ZhangPeng
* @Date 2021/1/7
* @Description do-while
*/
public class Demo2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("张浩上午学习理论,下午上机编程");
System.out.println("老师判断是否合格:");
boolean isPassed = input.nextBoolean();
while (!isPassed){
System.out.println("张浩上午学习理论,下午上机编程");
System.out.println("老师判断是否合格:");
isPassed = input.nextBoolean();
}
}
}
do-while循环
示例(题目同while)
import java.util.*;
/**
* @Author ZhangPeng
* @Date 2021/1/7
* @Description do-while
*/
public class Demo3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean isPassed = false;
do {
System.out.println("张浩上午学习理论,下午上机编程");
System.out.println("老师判断是否合格[合格(true)/不合格(false)]:");
isPassed = input.nextBoolean();
}while (!isPassed);
}
}
while循环和do-while循环的区别
for循环
语法和执行顺序
示例
import java.util.*;
/**
* @Author ZhangPeng
* @Date 2021/1/7
* @Description // 统计5门课成绩,并计算平均分
*/
public class Demo5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入学生姓名:");
String name = input.next();
int total = 0;
for (int i=1;i<=5;i++){
System.out.print("请输入5门课中第" + i + "门课的成绩:");
int score = input.nextInt();
total += score;
}
System.out.println(name + "平均分为:" + total/5.0);
}
}