按照闵老师的教程,今天是一个综合任务。随机生成学生成绩,并找出成绩最好、最差的同学,挂科的同学不参加评比。原博客地址:https://blog.csdn.net/minfanphd/article/details/116933803
package basic;
import java.util.Arrays;
import java.util.Random;
/**
*
* This is the tenth code, also the first task.
*
* @author WX873
*
*/
public class Task1 {
/**
* ***********************************************
* The entrance of the program.
*
* @param args Not used now.
*/
public static void main(String args[]) {
task1();
}//of main
/**
* ********************************************
* Method unit test.
* ********************************************
*/
public static void task1() {
//Step 1. Generate the data with n students and m courses.
//Set these value by yourself.
int n = 10;
int m = 3;
Random tempRandom = new Random();
int upperBound = 100;
int lowerBounder =50;
int threshold = 60;
int[][] data = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
data[i][j] = lowerBounder + tempRandom.nextInt(upperBound - lowerBounder);
}//of for j
}//of for i
System.out.println("The data is :\r\n" + Arrays.deepToString(data));
//Step 2. Compute the total score of each student.
int[] tempResult = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (data[i][j] < threshold) {
tempResult[i] = 0;
break;
}//of if
tempResult[i] += data[i][j];
}//of for j
}//of for i
System.out.println("The total score are :\r\n" + Arrays.toString(tempResult));
//Step 3. Find the best and worst student.
int tempBestIndex = -1;
int tempWorstIndex = -1;
int BestScore = 0;
int WorstScore = m * upperBound + 1;
for (int i = 0; i < n; i++) {
if (tempResult[i] == 0) {
continue;
}//of if
if (tempResult[i] > BestScore) {
BestScore = tempResult[i];
tempBestIndex = i;
}//of if
if (tempResult[i] < WorstScore) {
WorstScore = tempResult[i];
tempWorstIndex = i;
}//of if
}//of for i
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 score:" + BestScore);
}//of if
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 score:" + WorstScore);
}//of if
}//of task1
}//of Task1
这次新学了生成随机数,就是random()方法。随着学习,不断觉得代码的合理性自己还不能把握住。练习本篇博客内容的时候,先看了一遍程序,然后自己试着写。初始化的时候原程序worstScore = m*upperBound + 1,自己写的时候初始化为0了。虽然对程序没啥影响,但是想了一下还是原来的更合理些。最大值初始值设为最小,最小值的初始值设为最大。这里只是举了一个例子,还有原博客中将upperBound设置为65去找bug,为啥会想到去这么做?包括挂科的同学,总成绩直接为零,这个地方,一看到就恍然大悟,自己在没看代码的时候没想到。