Day code 300 lines learning notes Day 10

1. Integrated task I

Task content: Students' scores are stored in a matrix, where rows represent students and lists show subjects. For example, the 0 th line of Chinese and English indicates the student's score. Task requirements:

1. Random generation of student scores, with an interval of [50, 100].

2. Find the best and worst students. However, students who fail in the course will not participate in the evaluation.

1. Code demonstration

package basic;

import java.util.Arrays;
import java.util.Random;

/**
 * This is the tenth code, also the first task.
 * 
 * @author WU JUN 2298320301@qq.com.
 */
public class Day10 {
	/**
	 *********************
	 * 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 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(100 - 50);
			} // 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 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 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

1.2 code explanation

1. We start with the main function. There is only one task1 method in the main function of the above code, so next we jump to the task1 method for analysis.

2. First, the task1 method does not need to pass in any parameters and does not return a value. Next, analyze the internal content of the function. The function defines and initializes some columns of local variables at the beginning (only works in the function). Looking down, we will encounter a code called Random tempRandom = new Random(). This code is used to create an object. The random method comes with Java, but you need to write import Java at the top of the code before using it util. Random statement. Supplement: random return value is a pseudo-random selected number.

The next step is the nested loop of two for statements. The overall function of this loop is to fill the obtained random numbers into our matrix array. Among them, we need to pay attention to data [i] [J] = Lowerbound + temprandom Nextint (100 - 50) statement. The function of this statement is to make students' grades between 50 and 100. tempRandom. The function of nextint (100 - 50) is to randomly obtain one from [0 ~ 50). Next is the second nested for loop. This for loop is mainly used to calculate the total score of each student and store the total score into the totalScores array. We need to note that there is an if judgment statement inside this nested loop. The judgment condition of the if statement is that when the score of a student in a subject is less than 60, the total score is recorded as zero. There is also a break statement in the if statement. Let's understand how the program will run after the break statement is executed. When the if judgment conditions are met, the program will jump out of the for loop at the innermost level instead of skipping the whole nested loop. Supplement: temprandom I made some modifications to the parameters of nextint (100 - 50) function to facilitate the observation of the best data record after operation.

3. Next, after the task1 function, you need to filter out the data of the students with the best and worst grades. In the previous second nested for loop statement, we have calculated the total score of each student and stored the total score in the totalScores array, so we only need to traverse the array and select the maximum and minimum values. The specific implementation method is to define two variables tempBestScore and tempWorstIndex respectively to save the current best and worst scores, and also define two variables tempBestIndex and tempWorstScore to record the row subscripts of the best and worst scores in the data array of the general data table. Note: it is easy to understand when screening the total score of the students with the best score, but there are some problems when screening the total score of the students with the worst score. tempWorstScore = m * upperBound + 1 this code will be used to filter the starting boundary of the worst scores, which is too low to filter out the data of the worst students. It is suggested that it is more reasonable to change it into the total score.

4. Finally, the conditional printing program of some columns. We initially set the initial values of tempBestIndex and tempWorstScore to - 1. When the best score and the worst score are not selected, the relevant prompt information of search failure will be printed. If they are selected, the student's score data of each subject will be printed.

2. Operation results

3. Summary

Generally speaking, the whole mission goal is not particularly complex, and there should be no big problem in achieving it. In today's code, the new operation of creating objects makes me feel a little bit like learning java before. It also reminds me of the major features of Java, such as encapsulation, inheritance and polymorphism.

Keywords: Java Eclipse

Added by robburne on Sat, 05 Mar 2022 14:13:55 +0200