Enter the scores of a student's 5 courses and calculate the average score. If the entry of a certain score is negative, stop entry and prompt entry error

1.1. Training description

Enter the scores of a student's 5 courses and calculate the average score. If the entry of a certain score is negative, stop entry and prompt entry error.

1.2. Description of operation steps

  1. Create keyboard entry objects

  2. Define the variables sum (total score) and avg (average score) of type int, the initial value of the two variables is 0, and the variable name of String type represents the name of the student

  3. Define the variable flag of the boolean type (indicating whether the student's 5 scores are entered correctly, if one of the scores is negative, the negative value is true, indicating an entry error), the initial value is false

  4. Use the for loop to enter 5 results

    (1) If the current score is less than 0, the flag is assigned to true, and the for loop is terminated

    (2) Otherwise, if the currently entered score>=0, the cumulative sum

  5. Print result

​ (1) If flag is true, print input errors

​ (2) Otherwise, if flag is false, print the total score and average score

import java.util.Scanner;
public class Kehou1{
    
    
	public static void main(String[] args){
    
    
	    //思路一
		// Scanner sc = new Scanner(System.in);
		// int sum = 0;
		// int avg = 0;
		// System.out.println("请输入学生姓名:");
		// String name = sc.next();
		
		// for(int i = 1;i <=5;i++){
    
    
			// System.out.println("请输入"+i+"门成绩:");
			// int num = sc.nextInt();
			// if(num<0){
    
    
				// System.out.println("客官不可以");
				// break;
			// }else{
    
    
				// sum += num;
			// }
		// }
		// if(i == 5){
    
    
			
			// System.out.println(name+"总分为:"+sum);
			// System.out.println(name+"平均分分为:"+sum/5);
		// }
		//思路2
		boolean flag = false;//false表示没有不合法的数据,true表示有不合法的数据
		Scanner sc = new Scanner(System.in);
		int sum = 0;
		int avg = 0;
		for(int i = 1;i <=5;i++){
    
    
			System.out.println("请输入"+i+"门成绩:");
			int num = sc.nextInt();
			//判断num是否合法,如果不合法,则直接修改标志位 true表示有不合法的数据
			if(num<0){
    
    
				flag = true;
				break;
			}
			sum += num;//代码能执行到这里,就证明a是合法的
		}
		//根据flag状态,确定是否要求平均值
		if(flag==true){
    
    
			//说明有不合法存在
			System.out.println("亲,别乱来");
		}else{
    
    
			//说明合法
			System.out.println(name+"平均分分为:"+sum/5);
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_42073385/article/details/107722153