循环结构
定义:在特定的条件下重复的去做一件事
1. while语句
先判断,后执行
//循环必要条件:1..起始值2..循环条件3..循环体(满足条件执行的代码)4..迭代
//输出十遍我很帅
int n = 1;
while(n <= 10) {
System.out.println("我很帅!第" + n + "遍。");
n++;
}
System.out.println("========================");
//输出10—1
int j = 10;
while(j>=1) {
System.out.println(j);
j--;
}
System.out.println("====================");
//输出12以内的偶数
int i = 2;
while(i<=12) {
System.out.println(i);
i+=2;
}
System.out.println("=====================");
//输出1o以内的偶数之和
int sum = 0;
int k = 2;
while(k<=10) {
sum+=k;
k+=2;
}
System.out.println(sum);
//检查学生学习任务是否合格,不合格惩罚,继续进行,合格结束
Scanner in = new Scanner(System.in);
System.out.println("成绩是否合格:(y/n)");
String kemu = in.next();
int count = 0;
while(!"y".equals(kemu)) {
count++;
System.out.println("成绩不合格惩罚。");
System.out.println("成绩是否合格:(y/n)");
kemu = in.next();
}
System.out.println("终于合格了!惩罚次数:" + count);
2. do-while 语句
先执行,后判断.先不管条件是否成立都先执行一遍,再进行判断
Scanner in = new Scanner(System.in);
String answer;
do {
System.out.println("练习敲代码一遍!");
System.out.println("是否合格?y/n");
answer = in.next();
} while ("n".equals(answer));
System.out.println("合格了,不用继续练习了!");
int i = 1;
do {
System.out.println(i);
i++;
} while (i<=100);
System.out.println("******************");
int j = 2;
do {
System.out.println(j);
j+=2;
} while (j<=10);
3.for语句
在知道循环次数的情况下使用
//10-1
for(int i = 10;i>=1;i--) {
System.out.println(i);
}
System.out.println("************************");
//10 8 6 4 2
for(int j = 10;j >= 2;j-=2) {
System.out.println(j);
}
System.out.println("**********************");
//100以内偶数和
int sum = 0;
for(int k = 2;k<= 100;k+=2) {
sum+=k;
}
System.out.println(sum);
//循环输入10个同学的成绩,得到80分以上比例
Scanner in = new Scanner(System.in);
int score;
int count = 0;
for(int i = 1;i<=10;i++) {
System.out.print("请输入第" + i + "个同学的成绩:");
score = in.nextInt();
if(score > 80) {
count++;
}
}
System.err.println("80分以上的同学占" +(count*10.0) + "%" );
4.foreach
Scanner in = new Scanner(System.in);
int score[] = new int[5];
int sum = 0;
for(int i = 0;i<score.length;i++) {
System.out.println("请输入第" + (i+1) + "个同学的分数:");
score[i] = in.nextInt();
sum += score[i];
}
//foreach或者叫加强for循环
//注意:foreach只能用于数组或集合的遍历
for (int i : score) {
System.out.print(" " + i);
}
5. 跳转语句
-
break
-
中断,遇到break跳出循环,循环结束;
for(int i = 1;i<10;i++){ if(i==5){ break; } } //结果1 2 3 4
-
-
continue
- 继续,遇到continue跳过本次循环,直接继续下下一次循环
//循环输入10个同学的成绩,得到80分以上比例 Scanner in = new Scanner(System.in); int score; int count = 0; for(int i = 1;i<=10;i++) { System.out.print("请输入第" + i + "个同学的成绩:"); score = in.nextInt(); if(score < 80) { continue; } count++; } System.out.println("80分以上的同学占" +(count/10.0)*100 + "%");