while循环
while循环 :先判断再执行
while(循环条件){ 循环操作; }
三要素:循环的初始值; 循环条件; 循环条件的变化
public class Day01 {
public static void main(String[] args) {
int i=1;
while(i<=100){
System.out.println("第"+i+"次"+"好好学习天天向上!");
i++;
}
}
}
public class Sum {
public static void main(String[] args) {
int i=2;
int sum=0;
while(i<=100){
sum+=i;
i+=2;
}
System.out.println(sum);
}
}
do-while循环 先执行再判断 至少执行一次
do{
执行内容;
}while(循环条件);
public class Day03 {
public static void main(String[] args) {
String flag="no";
do{
System.out.println("合格啦吗"+flag);
flag="yes";
}while(!flag.equals("yes"));
System.out.println(flag);
}
}
课后作业:
public class Day02 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String ans=sc.next();
while(!ans.equals("yes")){
System.out.println("上午学习理论");
System.out.println("下午上机编程");
System.out.println("合格啦吗"+ans);
ans=sc.next();
}
System.out.println("完成学习任务");
}
}
for循环
/**
- 输出加法表
*/
public class Day02 {
public static void main(String[] args) {
for(int i=0;i<7;i++){
System.out.println(i+"+"+(6-i)+"="+6);
}
}
}
public class Day03 {
public static void main(String[] args) {
int sum=0;
for(int i=1;i<=100;i++){
if(i%3!=0){
sum+=i;
}
}
System.out.println(sum);
}
}
break语句:结束本层for循环
public class Day04 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int grade,avg,sum=0;
for(int i=1;i<=5;i++){
grade=sc.nextInt();
if(grade<0){
break;
}else{
sum+=grade;
}
}
avg=sum/5;
System.out.println(avg);
}
}
public class Day05 {
public static void main(String[] args) {
int total=0;
for(int i=1;i<=10;i++){
total+=i;
if(total>=20){
break;
}
}
System.out.println(total);
}
}
continue 结束本次for循环/当前for循环
public class Day06 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int score;
int sum=0;
for(int i=0;i<5;i++){
score=sc.nextInt();
if(score<=80){
continue;
}
sum+=score;
}
System.out.println(sum);
}
}
public class Day07 {
public static void main(String[] args) {
int sum=0;
for(int i=1;i<=10;i++){
if(i%2!=0){
continue;
}
sum+=i;
}
System.out.println(sum);
}
}
for循环+if判断
public class Sum {
public static void main(String[] args) {
int sum=0;
for(int i=1;i<=100;i++){
if(i%2!=0)
sum+=i;
}
System.out.println(sum);
}
}
循环总结:
1.while可以一次都不执行 do-while至少执行一次
2.while和do-while适用于循环条件未知的情况
3.for循环适用于循环条件已知的情况