学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 0 行表示第 0 个学生的数学、语文、英语成绩。要求:
1.进行学生成绩的随机生成, 区间为 [50, 100].
2.找出成绩最好、最差的同学。但有挂科的同学不参加评比.
10.1 实际代码中,for 和 if 是最常见的, switch 和 while 使用少得多.
10.2 使用了 continue, 它是指继续跳过本次循环后面的代码,直接进入下一次循环. 而 break 是跳出整个循环体.
10.3 为了随机数,迫不得已提前使用了 new 语句生成对象.
10.4 通过数据测试找出程序中的 bug.
package basic;
import java.util.*;
public class student {
public static void main(String args[]) {
task1();
}
//task 函数
public static void task1() {
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 100;
int threshold = 60;
//注意生成随机数的方法
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);
}
}
System.out.println("The data is:"+ Arrays.deepToString(data));
//比较每一个学生的成绩
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];
}
}
System.out.println("The total Scores are:" + Arrays.toString(totalScores));
//找出最好和最坏的学生
int tempBestIndex = -1;
int tempWorstIndex = -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;
}
}
// 输出学号和分数
if(tempBestIndex == -1) {
System.out.println("Can not find the best student. All have failed");
}
else {
System.out.println("The best student is NO." + tempBestIndex + " with Score:"+Arrays.toString(data[tempBestIndex]));
}
if(tempWorstIndex == -1) {
System.out.println("Can not find the worst student. All student hava failed");
}
else {
System.out.println("The worst student is NO." + tempWorstIndex + " with Score:"+Arrays.toString(data[tempWorstIndex]));
}
}
}
我的感受:
第一章节
已经学完了,知识上没有多大问题。我的主要不足在于所知道的类太少了,而且代码书写很不规范。基础花不了多少时间,但是一定要牢靠,形成统一。
以后的学习中我会额外拓展知识面,基础规范慢慢抓。