3. 流程控制break与continue

流程控制

  1. break:终止、跳出switch、循环结构
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("循环结束");
		
	}
}
import java.util.Scanner;

public class TestAverageScore {
	public static void main(String[] args) {
    // 现有一个班级的5名学生,请通过控制台输入5名学生的分数,求平均数
		Scanner input = new Scanner(System.in);
		//如果输入过程中,存在非法数据,则整班成绩作废
		
		boolean flag = true;//true 代表合法
		double sum = 0D;
		
		for(int i = 1 ; i <= 5 ; i++){
			System.out.println("请输入第" + i + "学生的成绩:");
			
			double score = input.nextDouble();
			if(score < 0 || score > 100) {
				
				flag = false;// 存在非法数据
				break;
	
			}
			sum += score;
		}
		if(flag) {
			double average = sum/5;
			System.out.println(average);
		}else {
			System.out.println("输入有误,请重新输入!");
		}
	}
}
  1. continue:结束本次、进入下一次循环
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("循环结束");
	}
}
import java.util.Scanner;

public class TestContinue {
	public static void main(String[] args) {
    // 现有一个班级的5名学生,请通过控制台输入5名学生的分数,求平均数
		Scanner input = new Scanner(System.in);
		//如果输入过程中,存在非法数据,则整班成绩作废
		
		double sum = 0D;
		
		for(int i = 1 ; i <= 5 ; ){
			
			System.out.println("请输入第" + i + "学生的成绩:");
			
			double score = input.nextDouble();
			
			if(score < 0 || score > 100) {
				
				continue;
				
			}
			
			sum += score;
			i++;
		}
		
		double avg = sum / 5;
		
		System.out.println(avg);
	}
}
  1. 总结
import java.util.Scanner;

public class TestGuess {
	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		
		// 人机猜拳(1.剪刀 2.石头 3. 布)
		
		int cCount = 0;//电脑计数器
		int pCount = 0;// 玩家计数器
		
		for(int i == 1; i <= 3; ) {
			
		int computer = ((int)(Math.random() * 10)) % 3 + 1 ;
		
		System.out.println( ("请输入猜拳的编号:");
		
		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(you win");
			pCount++;
		}else {
				System.out.println("you failure");
				ccount++;
			}
		if(cCount == 2 || pCount == 2) {
			break;
		}
		i++;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/zhu_fangyuan/article/details/106822682