综合测试
package test;
import java.util.Arrays;
import java.util.Random;
/**
* This is the tenth code, also the first task.
*
* @author Michelle Min mitchellemin@163.com
*
*/
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 course.
// Set these values by yourself.
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 65;// Should be 100. This value is for testing.
int threshold = 60;
// Here we have to use an object to generate random numbers.
Random tempRandom = new Random();
//没太看懂这里new怎么用的
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);
//nextInt是package"java.util.Random"中算法么?
}// 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 replace 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;
// continue跳过本循环后面的代码,直接进入下一次循环
}// Of if
if (tempBestScore < totalScores[i]) {
tempBestScore = totalScores[i];
tempBestIndex = i;
}// Of if
// Attention: This if statement cannot be combined with the last one
// using "else if", because a student can be both the best and the
// worst. This bug was found while setting upeerBound = 65.
// 上界降低导致学生有不及格科目的概率增加,从而使得总分最高学生就是最低学生的概率增加,理论上无论upper多高都存在这种可能性
if (tempWorstScore > totalScores[i]) {
tempWorstScore = totalScores[i];
tempWorstIndex = i;
}// Of if
}// Of for i
// Step 4, Output the best student number and 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
}// Of task1