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("循环结束");
}
}
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("循环结束");
}
}
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);
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++;
}
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局结束\n",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局结束\n",i);
i++;
}
原文:https://www.cnblogs.com/FSHOU/p/13111426.html