任务要求:
学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 0 行表示第 0 个学生的数学、语文、英语成绩。要求:
- 进行学生成绩的随机生成, 区间为 [50, 100].
- 找出成绩最好、最差的同学。但有挂科的同学不参加评比.
注意:
①Arrays.toString 一维数组与Arrays.deepToString 多维数组的区别;
②continue与break的区别。
package test;
import java.util.Arrays;
import java.util.Random;
/**
* This is the first task.
*
* @author 前夜
*/
public class Task1 {
/**
*********************
* This is the entrance of the program.
*
* @param args not used now.
*********************
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
task1();
}// Of main
/**
*********************
* Method Unit test.
*********************
*/
public static void task1(){
// Step 1. Generate the data with n students and m courses.
// Set these values by yourself.
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 100;
int threshold = 60;
// Here wo have to use an object to generate the random numbers.
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));
// Step 2. Compute the total score of each student.
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;
} // Of if
totalScores[i] += data[i][j];
} // Of for j
} // Of for i
System.out.println("The total scores are:\r\n" + Arrays.toString(totalScores));
// Step 3. Find the best and worst student.
// Typical initialization for index: invalid value.索引的典型初始化:无效值。
int tempBestIndex = -1;
int tempWorstIndex = -1;
// Typical initialization for best and worst values.
// They must be replaced by valid values. 必须用有效值代替。
int tempBestScore = 0;
int tempWorstScore = m * upperBound + 1;
for (int i = 0; i < n; i++) {
// Do not consider failed students.
if (totalScores[i] == 0) {
continue;
} // Of if
if (tempBestScore < totalScores[i]) {
tempBestScore = totalScores[i];
tempBestIndex = i;
} // Of if
// Attention: This if statement cannot be combined with last one.
// Using "else if", because a student can be both the best and the worst.
// This bug while setting upperBound = 65.
if (tempWorstScore > totalScores[i]) {
tempWorstScore = totalScores[i];
tempWorstIndex = i;
} // Of if
} // Of for i
// Step 4. Output the student number and score.
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]));
} // 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 scores: " + Arrays.toString(data[tempWorstIndex]));
} // Of if
}// Of task1
}// Of class Task1