流程控制
break
终止、跳出switch、循环结构
package myFirstJava.java.测试;
public class TestBreak {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++){
if (i == 5){
break;//退出整个循环结构
}
System.out.println("当前循环次数:"+i);
}
System.out.println("循环结束");
}
}
continue
结束本次,进入下一次循环
package myFirstJava.java.测试;
public class TestContinue {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++){
if (i == 5){
continue;//跳过此次,进入下一次循环
}
System.out.println("当前循环次数:"+i);
}
System.out.println("循环结束");
}
}
场景项目
【成绩输入】continue
continue
依次录入五名学生的成绩,要求如果信息输入不合法则重新输入该条成绩,最后输出五名学生的平均成绩
package myFirstJava.java.测试;
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0D;
for(int i= 1; i <= 5; i++){
System.out.println("请输入第"+ i +"位学生的成绩:");
double score = input.nextDouble();
if(score < 0 || score > 100){
System.out.println("您的输入有误,请重新输入该学生的成绩");
i -= 1;//本次不计数
continue;//结束本次循环,进入下一次循环
}
sum += score;
}
double avg = sum / 5;
System.out.println("平均分为:"+avg);
代码改良
如果发现数据不合法,则此次循环不需要计数,也就是本次不需要 i++,那直接把i++写到循环最后,发现不合法输入,触发continue,本次循环中continue之后的代码都不会被执行了
double sum = 0D;
for(int i= 1; i <= 5;){
System.out.println("请输入第"+ i +"位学生的成绩:");
double score = input.nextDouble();
if(score < 0 || score > 100){
System.out.println("您的输入有误,请重新输入该学生的成绩");
continue;//结束循环
}
sum += score;
i++;
}
【剪刀石头布】break + continue
break,continue综合应用
人机剪刀石头布,要求三局两胜
package myFirstJava.java.测试;
import java.util.Scanner;
public class TestGuess {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int playerWin = 0;//记录人赢的次数
int computerWin = 0;//记录机器赢的次数
for(int i = 1; i <= 3;) {
int computer = ((int) (Math.random() * 10)) % 3 + 1;//取随机数
System.out.println("输入猜拳编号(1.剪刀 2.石头 3.布)");
int player = input.nextInt();
//比较
if(computer == player) {
System.out.println("平局,再来一次");
continue;
} else if((player == 1 && computer == 3) || (player == 2 && computer == 1) || (player == 3 && computer == 2)) {
System.out.println("人类赢");
playerWin ++;
if(playerWin ==2){
System.out.println("人类赢两局胜出");
break;
}
} else {
System.out.println("电脑赢");
computerWin ++;
if(computerWin ==2){
System.out.println("电脑赢两局胜出");
break;
}
}
System.out.printf("第%d局结束
",i);
i++;
}
}
}
代码改良
减少了代码冗余,减少了判断次数
int playerWin = 0;
int computerWin = 0;
for(int i = 1; i <= 3;) {
int computer = ((int) (Math.random() * 10)) % 3 + 1;
System.out.println("输入猜拳编号(1.剪刀 2.石头 3.布)");
int player = input.nextInt();
if(computer == player) {
System.out.println("平局,再来一次");
continue;
} else if((player == 1 && computer == 3) || (player == 2 && computer == 1) || (player == 3 && computer == 2)) {
System.out.println("人类赢");
playerWin +=1;
} else {
System.out.println("电脑赢");
computerWin +=1;
}
if(computerWin == 2){
System.out.println("电脑赢两局胜出");
break;
}else if(playerWin == 2){
System.out.println("人类赢两局胜出");
break;
}
System.out.printf("第%d局结束
",i);
i++;
}