一. 功能介绍
找出所有同学中成绩最好的和最差的,凡是有一科挂科,均不参加
1.先随机生成每位同学的成绩
2.计算每个同学的总分,若有一个门挂科,则总分为0
3.找出成绩最好和成绩最差的学生,并记录下来
4.输出成绩最好和成绩最差的学生
二.代码实现
package com.one;
import java.util.*;
public class Task1 {
public static void main(String args[]) {
task1();
}// of main
public static void task1() {
//n:学生个数,m:科目个数
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 100;
int threshold = 60;
//1.生成随机数
Random tempRandom = new Random();
int[][] data = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
data[i][j] = lowerBound + tempRandom.nextInt(upperBound - lowerBound);
} // of for j
} // of for i
System.out.println("The data is:\r\n" + Arrays.deepToString(data));
// 2.计算每个同学的成绩,如果出现挂科的,则总分记为0
int[] totalScores = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (data[i][j] < threshold) {
totalScores[i] = 0;
break;
}
totalScores[i] += data[i][j];
} // of for j
} // of for i
System.out.println("The total scores are:\r\n" + Arrays.toString(totalScores));
//3.找出成绩最好和最差的学生,但挂科的同学不参加
//设置最好和最差学生的索引均为-1
int tempBestIndex = -1;
int tempWorstIndex = -1;
//最好的成绩初始值为0
//最差成绩的初始值为全部科目满分+1
int tempBestScore = 0;
int tempWorstScore = m * upperBound + 1;
for (int i = 0; i < n; i++) {
//挂科,退出该循环,执行下一次循环
if (totalScores[i] == 0) {
continue;
}
//找出最大,最小,并记录索引位置
if (tempBestScore < totalScores[i]) {
tempBestScore = totalScores[i];
tempBestIndex = i;
}
if (tempWorstScore > totalScores[i]) {
tempWorstScore = totalScores[i];
tempWorstIndex = i;
}
} // of for i
//4.输出最好和最差成绩
if (tempBestIndex == -1) {
System.out.println("Cannot find best student. All students have failed.");
} else {
System.out.println("The best student is No." + tempBestIndex + " with scores: " + Arrays.toString(data[tempBestIndex]));
}
if (tempWorstIndex == -1) {
System.out.println("Cannot find worst student. All students have failed.");
} else {
System.out.println("The worst student is No." + tempWorstIndex + " with scores: " + Arrays.toString(data[tempWorstIndex]));
}
}// of task1
}// of class