编写一个程序,从键盘输入5个学生的分数(以非数字字符串结束),然后输出高于平均分的分数。

2025-04-16 07:19:25
推荐回答(1个)
回答1:

完整代码如下:

import java.util.*;
/**
 * 从键盘输入5个学生的分数(以非数字字符串结束),然后输出高于平均分的分数
 * @author young
 *
 */
public class He {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String reg="^[0-9]+$" ;
float[] s = new float[5];
int count = 0;
float avg = 0, sum = 0;
System.out.println("输入5个分数,以非数字结束:");
while(true){
String f = sc.nextLine();
if(f.matches(reg)){
s[count] = Integer.parseInt(f);
}else {
break;
}
count ++;
}
//计算平均数
for(int j=0;j            sum+=s[j];
            avg=sum/s.length;
       }
System.out.println("平均分是:" + avg);
//输入大于平均数的分数
System.out.print("大于平均分的分数是: ");
for(float temp : s){
if(temp > avg){
System.out.print("  " + temp);
}
}
}
}

 运行结果如下: