Java 8 以上(包含java8) Lambda 方式,这种方式比较简洁,代码如下:
import java.util.ArrayListimport java.util.List
import java.util.Scanner
public class App20 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in)
List<Float> scores = new ArrayList<>()
System.out.println("请输入10个人的成绩:")
for (int i = 0 i < 10 i++) {
scores.add(scanner.nextFloat())
}
float max = scores.stream().max((x, y) -> Float.compare(x, y)).get()
System.out.println("最高分:" + max)
float min = scores.stream().min((x, y) -> Float.compare(x, y)).get()
System.out.println("最低分:" + min)
float average = scores.stream().reduce(0.0f, Float::sum) / scores.size()
System.out.println("平均分:" + average)
scores.sort((x, y) -> Float.compare(x, y))
System.out.println("从小到大分数排序:")
scores.forEach(s -> System.out.print(s + " "))
long n = scores.stream().filter(r -> r > average).count()
System.out.println("\n高于平均分的有" + n + "个")
}
}
传统方式,如下:
import java.util.Arrayspublic class App21 {
public static void main(String[] args) {
float[] scores = new float[] { 10f, 9f, 8f, 7f, 6f, 5f, 4f, 3f, 2f, 1f }
float max = Float.MIN_VALUE
for(float score : scores) {
if (score > max) {
max = score
}
}
System.out.println("最高分:" + max)
float min = Float.MAX_VALUE
for(float score : scores) {
if (score < min) {
min = score
}
}
System.out.println("最低分:" + min)
float sum = 0
for(float score : scores) {
sum += score
}
float average = sum / scores.length
System.out.println("平均分:" + average)
// 从小到大排序
Arrays.sort(scores)
System.out.println("从小到大分数排序:")
for(float score : scores) {
System.out.print(score + " ")
}
int n = 0
for(float score : scores) {
if (score > average)
n++
}
System.out.println("\n高于平均分的有" + n + "个")
}
}
import java.util.ArrayList
import java.util.Collections
import java.util.Scanner
public class GradeList {
public static void main(String[] args) {
ArrayList<Integer>list = new ArrayList<>()
Scanner in = new Scanner(System.in)
int grade
System.out.print("请输入成绩,以空格隔开,键入-1结束:")
while ((grade = in.nextInt())!=-1){
if(grade>=0&&grade<=100)
list.add(grade)
}
System.out.println("实际统计的人数为:"+list.size()+"\n实际统计的成绩为:"+list)
System.out.println("平均分:"+getAvg(list))
System.out.println("最高分:"+getMax(list))
System.out.println("最低分:"+getMin(list))
System.out.println("不及格:"+getBad(list))
}
public static double getAvg(ArrayList<Integer>list){
int sum = 0
for (int i = 0i <list.size()i++) {
sum += list.get(i)
}
return (double)sum/list.size()
}
public static int getMax(ArrayList<Integer>list){
Collections.sort(list)
return list.get(list.size()-1)
}
public static int getMin(ArrayList<Integer>list){
Collections.sort(list)
return list.get(0)
}
public static ArrayList getBad(ArrayList<Integer>list){
Collections.sort(list)
ArrayList<Integer>badGradeList = new ArrayList<Integer>()
for (int index=0index <list.size()index++) {
int grade = list.get(index)
if (grade<60)
badGradeList.add(grade)
}
return badGradeList
}
}
main方法
求平均、最高、最低、不及格方法
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)