一、循环的缘由
在某种场景中,遇到多次重复做同一事件的情况,需要使用循环结构,可以提高效率。
二、循环的定义
生活中我们经常会遇到循环,比如:打印100份笔记、沿着操场跑步10圈、错误的英文单词罚抄50遍等等。从中可以总结出一个特点,循环需要有条件和操作,如打印100份讲义,“100份讲义”是循环条件,“打印”是循环操作。
三、while循环结构
题目:打印50份试卷
public static void main(String[] args) { int a=1; while(a<5){ System.out.println("打印"+a+"份试卷"); } a++; }
四、do-while循环结构
题目:
经过几天的学习,老师给张浩一道测试题,
让他先上机编写程序完成,
然后老师检查是否合格。如果不合格,则继续编写。……
public static void main(String[] args) { String answer=""; do{ System.out.println("上机编写程序"); System.out.println("检查是否合格:(合格/不合格)"); Scanner hd = new Scanner(System.in); answer=hd.next(); System.out.println("继续编写"); }while("不合格".equals(answer)); System.out.println("通过测试"); }
五、for循环结构
题目:
循环输入某同学S1结业考试的5门课成绩,并计算平均分
public static void main(String[] args) { int score=0; double sum=0.0; double avg=0.0; for(int i=0;i<5;i++){ System.out.println("请输入第"+(i+1)+"门成绩"); Scanner input = new Scanner(System.in); score=input.nextInt(); sum=sum+score; } System.out.println("和"+sum); avg=sum/5; System.out.println("平均成绩:"+avg); }