for循环嵌套
九九乘法表
版本一:
for(int i = 1;i<=9;i++){
for(int j = 1;j<=i;j++){
System.out.print(j + "x" + i + "=" + (j*i) + "\t");
}
System.out.println();
}
版本二:
for(int i = 1;i<=9;i++){
for(int k = 1;k<i;k++){
System.out.print("\t");
}
for(int j = i;j<=9;j++){
System.out.print(i + "x" + j + "=" + (j*i) + "\t");
}
System.out.println();
}
while循环
语法结构:
while(表达式){ ...代码块... }
理解:
表达式的结果必须是boolean true-执行代码块 false-跳出while循环
死循环:
while(true){ System.out.println("死循环"); }
案例:我有个梦想,每月存3000,每年递增1000元,多少个月后存满20万
int money = 3000;
int month = 0;
int allMoney = 0;
while(allMoney < 200000){
allMoney += money;
if(month != 0 && month%12==0){
money+=1000;
}
month++;
}
System.out.println(month + "个月后存满20万 " + money);
do-while循环
语法结构:
do{
...代码块...
}while(表达式);
理解:
表达式的结果必须是boolean
true-执行代码块
false-跳出do-while循环
执行流程:
1.执行代码块
2.判断表达式
true - 执行代码块,重复第2个步骤
false - 跳出do-while循环
做实验:
do{
System.out.println("键盘敲烂,月薪过万");
}while(false);
死循环:
do{
System.out.println("死循环");
}while(true);
案例:朝阳参加学校组织的歌咏比赛,大赛在即,
老师建议:先彩排一次,如果很令人满意,以后就不用彩排了,
否则每天都排,直到现场表现满意为止!
Scanner scan = new Scanner(System.in);
String str;
do{
System.out.println("朝阳:\" 旋转跳跃我闭着眼...\"");
System.out.println("朝阳:\" 何老师,您满意了吗?\"");
str = scan.next();
}while(!str.equals("满意"));
for vs while vs do-while
语法结构的区别:
for(初始化变量;判断条件;更新变量){
}
while(判断条件){
}
do{
}while(判断条件);
注意:
循环中的判断条件的结果都是boolean,true-循环,false-跳出循环
执行顺序的区别:
for:先判断,再执行
while:先判断,再执行
do-while:先执行一遍,再判断
应用场景的区别:
循环次数固定的情况:for
循环次数不固定的情况,先判断再执行:while
循环次数不固定的情况,先易运行一遍再判断:do-while
特殊的流程控制语句
break:作用在循环中,代表跳出整个循环
案例:循环录入麻生希同学5门课的成绩并计算平均分,
如果某分数录入为负,停止录入并提示。
Scanner scan = new Scanner(System.in);
boolean flag = true;//true-正常录入 false-录入错误
double sum = 0;
for(int i = 1;i<=5;i++){
System.out.println("请输入第" + i + "门成绩:");
double score = scan.nextDouble();
if(score < 0){
flag = false;
break;
}
sum += score;
}
if(flag){
double avg = sum/5;
System.out.println("平均分为:" + avg);
}else{
System.out.println("分数为负数,停止录入");
}
continue:作用在循环中,代表跳过循环体剩余的部分,进入到下一次循环
案例:循环录入Java课5名学生的成绩,统计分数大于等于80分的学生比例。
Scanner scan = new Scanner(System.in);
int num = 0;//记录大于等于80分学生的人数
for(int i = 1;i<=5;i++){
System.out.println("请输入第" + i + "名学生的成绩:");
double score = scan.nextDouble();
if(score < 80){
continue;
}
num++;
}
System.out.println("大于等于80分学生的比例为:" + (num/5.0*100) + "%");
return:单独编写,代表结束当前方法
System.out.println("1");
System.out.println("2");
if(true){
return;
}
System.out.println("3");
System.out.println("4");
lable:给循环做标记
需求:双层for循环,外层循环5次,内层循环3次,
当外层循环到第3次,在内层循环中结束掉外层循环
a:for(int i=1;i<=5;i++){
for(int j=1;j<=3;j++){
if(i == 3){
break a;
}
System.out.println(i + " -- " + j);
}
}