Java学习之日撸代码300行
任务计划
第1天:环境搭建
第2天:基本算数操作
第3天:基本if语句
第4天:闰年的计算
第5天:基本Switch语句
第六天:for循环语句
第七天:矩阵元素相加
第八天:while语句
第九天:矩阵相乘
第十天:综合训练
第一天:
之前通过同学对Java的环境配置有一定的了解,也进行过环境配置,安装了JDK
跟闵老师所发布的有不同之处,今天我先用之前配置的环境进行了编写HelloWorld代码回顾
运行也正常,明日将进行闵老师所发布的进行环境配置,并完成第二天的内容
第二天:
今日首先完成了对Eclipse的环境搭建,对eclipse软件语言进行了一个更改,方便今后使用
今日根据闵老师学习内容完成了第二天的基本算数操作学习,完成代码及结果如下:
运行没有问题,完成今日学习
今日遇到问题:仍然对eclipse软件操作不熟练,自己编写代码仍有问题,需要看老师发布的代码才能完成操作,自己有时间将会多敲代码,多熟悉Java语言
第三天:
学习使用基本if语句,通过简单的if语句对其进行了解,对num1的数字变换可以得到不同的num2结果
package basic;
public class IfStatement {
/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
int num1, num2;
num1 = -5;
if (num1 >= 0) {
num2 = num1;
} else {
num2 = -num1;
}
System.out.println("The absolute value of " + num1 + " is " + num2);
num1 = -3;
if (num1 >= 0) {
num2 = num1;
} else {
num2 = -num1;
}
System.out.println("The absolute value of " + num1 + " is " + num2);
num1 = 6;
System.out.println("The absolute value of " + num1 + " is " + abs(num1));
num1 = -8;
System.out.println("The absolute value of " + num1 + " is " + abs(num1));
}
/**
*********************
* The absolute value of the given parameter.
*
* @param value The given value.
*********************
*/
public static int abs(int value) {
if (value >= 0) {
return value;
} else {
return -value;
}
}
}
运行结果:
近日通过对if语句的学习,对其有了简单的认识,尝试将闵老师发的代码对比自己网上搜到的代码进行了一定程度的简化
今日疑惑:不明白在输出语句中num1两端为何要有+号,不清楚最后一段if语句为何需要,在删除后程序运行就出现了错误
第四天:
今天学习闰年计算,同样也属于if语句逻辑
本次闰年计算采用了两种方法
package wyb;
public class LeapYear {
public static void main(String args[]) {
//Test isLeapYear
int tempYear=2021;
System.out.print(""+tempYear+"is");
if(!isLeapYear(tempYear)) {
System.out.print("NOT");
}//Of if
System.out.println("a leap year.");
tempYear=2000;
System.out.print(""+tempYear+"is");
if (!isLeapYear(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
tempYear = 2100;
System.out.print("" + tempYear + " is ");
if (!isLeapYear(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
tempYear = 2004;
System.out.print("" + tempYear + " is ");
if (!isLeapYear(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
// Test isLeapYearV2
System.out.println("Now use the second version.");
tempYear = 2021;
System.out.print("" + tempYear + " is ");
if (!isLeapYearV2(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
tempYear = 2000;
System.out.print("" + tempYear + " is ");
if (!isLeapYearV2(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
tempYear = 2100;
System.out.print("" + tempYear + " is ");
if (!isLeapYear(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
tempYear = 2004;
System.out.print("" + tempYear + " is ");
if (!isLeapYearV2(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
}// Of main
public static boolean isLeapYear(int paraYear) {
if ((paraYear % 4 == 0) && (paraYear % 100 != 0) || (paraYear % 400 == 0)) {
return true;
} else {
return false;
} // Of if
}// Of isLeapYear
public static boolean isLeapYearV2(int paraYear) {
if (paraYear % 4 != 0) {
return false;
} else if (paraYear % 400 == 0) {
return true;
} else if (paraYear % 100 == 0) {
return false;
} else {
return true;
} // Of if
}// Of isLeapYear
}// Of class LeapYear
运行结果如下:
第五天:
Switch语句用来实现多分支判断,其原理是跳转到case位置执行剩下所有的语句,直到最后或遇见break为止,switch中的default,一般用在最后,表示非以上的任何情况。
闵老师所给的成绩分等级代码来举例switch语句,代码如下:
package day5;
public class Switch {
public static void main(String args[]) {
scoreToLevelTest();
}// Of main
public static char scoreToLevel(int paraScore) {
// E stands for error, and F stands for fail.
char resultLevel = 'E';
// Divide by 10, the result ranges from 0 to 10
int tempDigitalLevel = paraScore / 10;
// The use of break is important.
switch (tempDigitalLevel) {
case 10:
case 9:
resultLevel = 'A';
break;
case 8:
resultLevel = 'B';
break;
case 7:
resultLevel = 'C';
break;
case 6:
resultLevel = 'D';
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
resultLevel = 'F';
break;
default:
resultLevel = 'E';
}// Of switch
return resultLevel;
}// of scoreToLevel
public static void scoreToLevelTest() {
int tempScore = 100;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
tempScore = 91;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
tempScore = 82;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
tempScore = 75;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
tempScore = 66;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
tempScore = 52;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
tempScore = 8;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
tempScore = 120;
System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
}// Of scoreToLevelTest
}// Of class SwitchStatement
运行结果如下:
switch语句基本较好理解,运用到实际需要中需要多加练习,才能熟练运用,要注意break的位置
第六天:for循环
今天学习for循环语句,
for循环语句基本格式(初始化语句;判断条件语句;控制条件语句);循环语句体;
package for循环;
public class ForStatement {
/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
forStatementTest();
}// Of main
/**
*********************
* Method unit test.
*********************
*/
public static void forStatementTest() {
int tempN = 10;
System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
tempN = 0;
System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
int tempStepLength = 1;
tempN = 10;
System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: "
+ addToNWithStepLength(tempN, tempStepLength));
tempStepLength = 2;
System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: "
+ addToNWithStepLength(tempN, tempStepLength));
}// Of forStatementTest
/**
*********************
* Add from 1 to N.
*
* @param paraN The given upper bound.
* @return The sum.
*********************
*/
public static int addToN(int paraN) {
int resultSum = 0;
for (int i = 1; i <= paraN; i++) {
resultSum += i;
} // Of for i
return resultSum;
}// Of addToN
/**
*********************
* Add from 1 to N with a step length.
*
* @param paraN The given upper bound.
* @param paraStepLength The given step length.
* @return The sum.
*********************
*/
public static int addToNWithStepLength(int paraN, int paraStepLength) {
int resultSum = 0;
for (int i = 1; i <= paraN; i += paraStepLength) {
resultSum += i;
} // Of for i
return resultSum;
}// Of addToNWithStepLength
}// Of class ForStatement
输出结果:第一种结果是从1到10逐个相加得出结果,第2种情况1到10隔一个数相加
第七天:
今日学习矩阵元素相加,通过for双循环对矩阵进行赋值,i表示行,j表示列,矩阵内元素做总和再自行相加
package 矩阵;
import java.util.Arrays;
/**
* This is the seventh code. Names and comments should follow my style strictly.
*
* @author Fan Min minfanphd@163.com.
*/
public class MatrixAddition {
/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
matrixElementSumTest();
matrixAdditionTest();
}// Of main
/**
*********************
* Sum the elements of a matrix.
*
* @param paraMatrix The given matrix.
* @return The sum of all its elements.
*********************
*/
public static int matrixElementSum(int[][] paraMatrix) {
int resultSum = 0;
for (int i = 0; i < paraMatrix.length; i++) {
for (int j = 0; j < paraMatrix[0].length; j++) {
resultSum += paraMatrix[i][j];
} // Of for j
} // Of for i
return resultSum;
}// Of matrixElementSum
/**
*********************
* Unit test for respective method.
*********************
*/
public static void matrixElementSumTest() {
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++) {
for (int j = 0; j < tempMatrix[0].length; j++) {
tempMatrix[i][j] = i * 10 + j;
} // Of for j
} // Of for i
System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));
System.out.println("The matrix element sum is: " + matrixElementSum(tempMatrix) + "\r\n");
}// Of matrixElementSumTest
/**
*********************
* Add two matrices. Attention: NO error check is provided at this moment.
*
* @param paraMatrix1 The first matrix matrix.
* @param paraMatrix2 The second matrix matrix. It should have the same size as
* the first one.
* @return The addition of these matrices.
*********************
*/
public static int[][] matrixAddition(int[][] paraMatrix1, int[][] paraMatrix2) {
int[][] resultMatrix = new int[paraMatrix1.length][paraMatrix1[0].length];
for (int i = 0; i < paraMatrix1.length; i++) {
for (int j = 0; j < paraMatrix1[0].length; j++) {
resultMatrix[i][j] = paraMatrix1[i][j] + paraMatrix2[i][j];
} // Of for j
} // Of for i
return resultMatrix;
}// Of matrixAddition
/**
*********************
* Unit test for respective method.
*********************
*/
public static void matrixAdditionTest() {
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++) {
for (int j = 0; j < tempMatrix[0].length; j++) {
tempMatrix[i][j] = i * 10 + j;
} // Of for j
} // Of for i
System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));
int[][] tempNewMatrix = matrixAddition(tempMatrix, tempMatrix);
System.out.println("The new matrix is: \r\n" + Arrays.deepToString(tempNewMatrix));
}// Of matrixAdditionTest
}
运行结果如下:
第八天:矩阵相乘
矩阵相乘和相加原理相同,但需要用到三重for循环
package 王雁冰1;
import java.util.Arrays;
/**
* This is the eighth code. Names and comments should follow my style strictly.
*
* @author Fan Min minfanphd@163.com.
*/
public class MatrixMultiplication {
/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
matrixMultiplicationTest();
}// Of main
/**
*********************
* 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
/**
*********************
* Matrix multiplication. The columns of the first matrix should be equal to the
* rows of the second one.
*
* @param paraFirstMatrix The first matrix.
* @param paraSecondMatrix The second matrix.
* @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 cannot be multiplied.");
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 i
} // Of for j
return resultMatrix;
}// Of matrixMultiplicationTest
}// Of class MatrixMultiplication
运行结果:
第八天:while语句
今日学习while语句,while语句本质上可以替代for语句,但后者更为方便
今日while语句采用两种方法运行,第一种直接在while里运行,判断sum是否小于等于max,当sum大于max时自动结束循环;第二种是while里的判断条件为true,while会一直循环,在while循环体内加一个判断,当sum大于max时使用break跳出循环
代码如下:
package basic;
/**
* This is the nineth code. Names and comments should follow my style strictly.
*
* @author Fan Min minfanphd@163.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
两种方式运行结果相同:
第十天:综合训练
今日对前九天的学习进行一个综合训练,编写代码对学生成绩进行一个最优和最差的筛选,代码如下:
package basic;
import java.util.Arrays;
import java.util.Random;
/**
* This is the tenth code, also the first task.
*
* @author Fan Min minfanphd@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 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));
// 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
运行结果如下:
本题先用随机数生成一个十行三列的矩阵,表示十个学生的语数外成绩,随机数使用Random类,tempRandom.nextInt(50),表示在0-50范围内随机生成一个数字,然后生成的随机数加上50就可以表示区间[50,100]的分数。
双重循环计算每个学生的总分,如果该学生有一科成绩低于60分,那么总分赋值为0,不参与评比。
for循环找出成绩最好的学生和最差的学生,当遇到分数为0的学生时,使用continue语句略过,继续循环。