1.借助java.util.Random类来生成随机数
Random类包含两个构造方法:
a、public Random()
该构造方法使用一个和当前系统时间对应的相对时间有关的数字作为种子数,然后使用这个种子数构造Random对象。
b、public Random(long seed)
该构造方法可以通过制定一个种子数进行创建。
再次强调:种子数只是随机算法的起源数字,和生成的随机数字的区间无关。
2.问题:
a.该句代码是指生成upperBound到lowerBound区间类的整数吗?
b.没太懂这个问题是怎么解决的(当upperBound = 65时)
3.代码:
package yrx;
import java.util.Arrays;
import java.util.Random;
public class Task1 {
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 values by yourself.
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 65;// Should be 100.I use this value for testing.
int threshold = 60;
// Here we have to use an object to generate 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));
// Step2.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 the last one
// using "else if", because a student can be both the best and the
// worst. I found 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 student have failed.");
} else {
System.out.println(
"The best student is No." + tempBestIndex + " with score: " + 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 if
}// Of task1
}// Of class Task1
4.运行结果