提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在学习Java的第二周是将剩下的Java基础语法进行学习,并运用之前所学的基础语法进行一次的综合任务。
一、Day8:矩阵相乘
在矩阵的相乘之前需要了解矩阵相乘的条件和矩阵相乘后得到的新矩阵的是什么样子的,这样能够帮助我们能够更好的理解矩阵相乘的代码。
矩阵相乘的代码如下:
package day_08;
import java.util.Arrays;
import java.util.PrimitiveIterator.OfDouble;
/**
*
* This is the eighth code.
*
* @author Juncai Chen 3039808589@qq.com.
*
*/
public class MatrixMultiplication {
/**
****************
* The entrance of the program.
*
* @param args Not used now.
****************
*/
public static void main(String[] args) {
matrixMultiplicationTest();
}// of main
/**
****************
* Matrix multiplication.The Columns of the first matrix should be equal to the
* rows of the second one.
*
* @param paraFirstMatrix.
* @param paraSecondMatrix.
* @return the result matrix.
****************
*/
public static int[][] multiplication(int[][] paraFirstMatrix, int[][] paraSecondMatrix) {
int m = paraFirstMatrix.length;
int n = paraFirstMatrix[0].length;
int p = paraSecondMatrix[0].length;
// Step 1. Dimension check.
if (paraSecondMatrix.length != n) {
System.out.println("The two matrices can not multiply.");
return null;
} // of if
// Step 2. The loop.
int[][] resultMatrix = new int[m][p];
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < n; k++) {
resultMatrix[i][j] += paraFirstMatrix[i][k] * paraSecondMatrix[k][j];
} // of for k
} // of for j
} // of for i
return resultMatrix;
}
/**
****************
* Unit test for respective method.
****************
*/
public static void matrixMultiplicationTest() {
int[][] tempFirstMatrix = new int[2][3];
for (int i = 0; i < tempFirstMatrix.length; i++) {
for (int j = 0; j < tempFirstMatrix[0].length; j++) {
tempFirstMatrix[i][j] = i + j;
} // of for j
} // of for i
System.out.println("The first matrix is: \r\n" + Arrays.deepToString(tempFirstMatrix));
int[][] tempSecondmatrix = new int[3][2];
for (int i = 0; i < tempSecondmatrix.length; i++) {
for (int j = 0; j < tempSecondmatrix[0].length; j++) {
tempSecondmatrix[i][j] = i * 10 + j;
} // of for j
} // of for i
System.out.println("The second matrix is: \r\n" + Arrays.deepToString(tempSecondmatrix));
int[][] tempThirdMatrix = multiplication(tempFirstMatrix, tempSecondmatrix);
System.out.println("The third matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix));
System.out.println("Trying to multiply the first matrix with itself.\r\n");
tempThirdMatrix = multiplication(tempFirstMatrix, tempFirstMatrix);
System.out.println("The result matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix));
}// of matrixMultiplicationTest
}// of class MatrixMultiplication
得到的结果如下:
矩阵的相乘相比于矩阵的加法,难度有一点点的提升,在我们写关于矩阵的相乘的代码,需要具备一些线性代数中矩阵相乘的代码,由矩阵相乘的条件进一步推出for循环的限制次数,for循环的嵌套也是需要慢慢进行数学的推理,得到for嵌套的次数。
二、Day9:while语句
代码如下:
package day_09;
/**
* This is the ninth code.
*
* @author Juncai Chen 3039808589@qq.com.
*/
public class WhileStatement {
/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
whileStatementTest();
}// Of main
/**
*********************
* The sum not exceeding a given value.
*********************
*/
public static void whileStatementTest() {
int tempMax = 100;
int tempValue = 0;
int tempSum = 0;
// Approach 1.
while (tempSum <= tempMax) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
} // Of while
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
// Approach 2.
System.out.println("\r\nAlternative approach.");
tempValue = 0;
tempSum = 0;
while (true) {
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
if (tempMax < tempSum) {
break;
} // Of if
} // Of while
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
}// Of whileStatementTest
}// Of class WhileStatement
运行后的结果是:
一般情况下在明确知道循环的次数时用for循环更加的方便,死循环时用while更加的方便,for循环和while循环和do—while循环在绝大多数情况下可以相互转换。
注意:do-while语句是先执行在判断,而for语句和while语句是先判断在执行。do-while语句至少都会执行一次,例如:
三、Day:10:综合任务1
老师的综合任务中对题目的描述:
学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。
如:第 0 行表示第 0 个学生的数学、语文、英语成绩。
要求:
进行学生成绩的随机生成, 区间为 [50, 100]. 找出成绩最好、最差的同学。但有挂科的同学不参加评比。
1.准备
在这次的综合任务中我们需要用到java的Random库,我们可以在添加好src.zip件后,按住Ctrl键鼠标去点击Random,就能够进入定义好的Random类,Ctrl+O可以查看里面定义好的方法和变量。
在Random方法中给出nextInt的第二行注释中我们可以得出,nextInt方法是随机生成从0(包括)到指定值(不包括)的整数。也就是说生成的随机值是在[0,n)的区间内的。
2.代码实现
2.1初始化
// step1. Gengrate the data with n students and m scores.
// Set these values by yourself
int n = 10;
int m = 3;
int lowBound = 50;
int upperBound = 100;// Should be 100.I use this value for test.
int threshold = 60;
// Here we have to use an object to generate random numbers.
int[][] data = new int[n][m];
Random tempRandom = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
data[i][j] = lowBound + tempRandom.nextInt(upperBound - lowBound + 1);
} // of for j
} // of for i
因为nextInt方法中右边是开区间,而成绩为100分的也是需要放入我们的数组中的,我们进行了加1的操作。
2.2创建成绩数组
// 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
创建成绩数组是我们对有挂科的同学不进行统计,即将他的总成绩赋值为0。
2.3查询成绩
// Step 3. Find the best and worst student.
// Typical initialization for index:invalid index.
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
我们统计时将总分为0的学生跳过统计,在这里我们进行了事先给定极值的方法来帮助我们进行统计,也在统计之前将tempBestInt设置为-1,这也是我们在数组中在查询之前将索引的值设置为-1常见的操作,在后面得到的tempBest(Worst)Int就是总成绩最好(最差)的学生的学生的编号。
注意:我们的编号是从0开始的。
2.4代码总预览
package day_10;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
/**
*
* This is the tenth code.
*
* @author Juncai Chen 3039808589@qq.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() {
// step1. Gengrate the data with n students and m scores.
// Set these values by yourself
int n = 10;
int m = 3;
int lowBound = 50;
int upperBound = 100;// Should be 100.I use this value for test.
int threshold = 60;
// Here we have to use an object to generate random numbers.
int[][] data = new int[n][m];
Random tempRandom = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
data[i][j] = lowBound + tempRandom.nextInt(upperBound - lowBound + 1);
} // 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 index.
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 the 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 the 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
}
运行的结果是:
总结
在第十天的综合任务中,能够帮助我们更好的对之前所学的基本语法进行应用,也能够帮助我们对前几天所学的知识进行很好的复习。在后面我们将对基本的线性结构进行学习,由于涉及到了基本的数据结构,难度也是有了一定的提升,在后面的学习中难度只会越来越大,也更加考验我们学习的耐心。