日撸 Java 三百行(01-10天,基本语法)

目录

总述
01-10天,基本语法
11-20天,线性数据结构
21-30天,树与二叉树
31-40天,图
41-50天,查找与排序
51-60天,kNN 与 NB
61-70天,决策树与集成学习
71-80天,BP 神经网络
81-90天,CNN 卷积神经网络

第1天: 环境搭建

1.1 完成 Eclipse 的安装. 第一天嘛,把环境弄对就行了.
1.2 学习 package, import 和 println 语句. 其中, package 要与所建的包名(即文件夹名)一致.
1.3 编写HelloWorld.java. 一定要注意变量的写法.

警告: 成事起头难. 环境安装、第一个程序的运行如果有问题, 请及时与老手联系, 不要自己折腾!
如果身边没有老手, 可以看下 唐金玉的安装方案.

package basic;

/**
 * This is the first code. Names and comments should follow my style strictly.
 * @author Fan Min [email protected]. 
 */
public class HelloWorld {
	public static void main(String args[]) {
		System.out.println("Hello, world!");
	}//Of main
}//Of class HelloWorld

第 2 天: 基本算术操作

2.1 加、减、乘、除、整除、取余.
2.2 熟悉 println 的中阶用法.

package basic;

/**
 * This is the second code. Names and comments should follow my style strictly.
 * @author Fan Min [email protected]. 
 */
public class BasicOperations {
	public static void main(String args[]) {
		int tempFirstInt, tempSecondInt, tempResultInt;
		double tempFirstDouble, tempSecondDouble, tempResultDouble;
		
		tempFirstInt = 15;
		tempSecondInt = 4;
		
		tempFirstDouble = 1.2;
		tempSecondDouble = 3.5;
		
		//Addition
		tempResultInt = tempFirstInt + tempSecondInt;
		tempResultDouble = tempFirstDouble + tempSecondDouble;
		
		System.out.println("" + tempFirstInt + " + " + tempSecondInt + " = " + tempResultInt);
		System.out.println("" + tempFirstDouble + " + " + tempSecondDouble + " = " + tempResultDouble);
		
		//Subtraction
		tempResultInt = tempFirstInt - tempSecondInt;
		tempResultDouble = tempFirstDouble - tempSecondDouble;
		
		System.out.println("" + tempFirstInt + " - " + tempSecondInt + " = " + tempResultInt);
		System.out.println("" + tempFirstDouble + " - " + tempSecondDouble + " = " + tempResultDouble);
		
		//Multiplication
		tempResultInt = tempFirstInt * tempSecondInt;
		tempResultDouble = tempFirstDouble * tempSecondDouble;
		
		System.out.println("" + tempFirstInt + " * " + tempSecondInt + " = " + tempResultInt);
		System.out.println("" + tempFirstDouble + " * " + tempSecondDouble + " = " + tempResultDouble);
		
		//Division
		tempResultInt = tempFirstInt / tempSecondInt;
		tempResultDouble = tempFirstDouble / tempSecondDouble;
		
		System.out.println("" + tempFirstInt + " / " + tempSecondInt + " = " + tempResultInt);
		System.out.println("" + tempFirstDouble + " / " + tempSecondDouble + " = " + tempResultDouble);
		
		//Modulus
		tempResultInt = tempFirstInt % tempSecondInt;
		
		System.out.println("" + tempFirstInt + " % " + tempSecondInt + " = " + tempResultInt);
	}//Of main
}//Of class BasicOperations

第 3 天: 基本if 语句

3.1 if then else.
3.2 方法(函数)调用: 增加代码的复用性.
3.3 方法(函数)头部规范的注释, 是后期生成文档的基础.

package basic;

/**
 * The usage of the if statement.
 * 
 * @author Fan Min [email protected].
 */

public class IfStatement {
	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		int tempNumber1, tempNumber2;

		// Try a positive value
		tempNumber1 = 5;

		if (tempNumber1 >= 0) {
			tempNumber2 = tempNumber1;
		} else {
			tempNumber2 = -tempNumber1;
		} // Of if

		System.out.println("The absolute value of " + tempNumber1 + " is " + tempNumber2);

		// Try a negative value
		// Lines 27 through 33 are the same as Lines 15 through 19
		tempNumber1 = -3;

		if (tempNumber1 >= 0) {
			tempNumber2 = tempNumber1;
		} else {
			tempNumber2 = -tempNumber1;
		} // Of if

		System.out.println("The absolute value of " + tempNumber1 + " is " + tempNumber2);

		// Now we use a method/function for this purpose.
		tempNumber1 = 6;
		System.out.println("The absolute value of " + tempNumber1 + " is " + abs(tempNumber1));
		tempNumber1 = -8;
		System.out.println("The absolute value of " + tempNumber1 + " is " + abs(tempNumber1));
	}// Of main

	/**
	 *********************
	 * The absolute value of the given parameter.
	 * 
	 * @param paraValue The given value.
	 *********************
	 */
	public static int abs(int paraValue) {
		if (paraValue >= 0) {
			return paraValue;
		} else {
			return -paraValue;
		} // Of if
	}// Of abs
}// Of class IfStatement

第 4 天: 闰年的计算

4.1 if 语句的嵌套.
4.2 基本规律自行百度.
4.3 布尔类型.

package basic;

/**
 * The complex usage of the if statement.
 * 
 * @author Fan Min [email protected].
 */

public class LeapYear {
	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	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 (!isLeapYearV2(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

	/**
	 *********************
	 * Is the given year leap?
	 * 
	 * @param paraYear The given year.
	 *********************
	 */
	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

	/**
	 *********************
	 * Is the given year leap? Replace the complex condition with a number of if.
	 * 
	 * @param paraYear The given year.
	 *********************
	 */
	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 isLeapYearV2

}// Of class LeapYear

第 5 天: 基本switch 语句

5.1 Switch, case, break, default 的用法.
5.2 单元测试单独使用一个方法, main 方法里面的代码越少越好.

package basic;

/**
 * This is the fifth code. Names and comments should follow my style strictly.
 * 
 * @author Fan Min [email protected].
 */
public class SwitchStatement {
	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		scoreToLevelTest();
	}// Of main

	/**
	 *********************
	 * Score to level.
	 * 
	 * @param paraScore From 0 to 100.
	 * @return The level from A to F.
	 *********************
	 */
	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

	/**
	 *********************
	 * Method unit test.
	 *********************
	 */
	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

第 6 天: 基本for 语句

6.1 循环语句是程序的核心.
6.2 算法的时间复杂度一般根据循环语句来计算.

package basic;

/**
 * This is the sixth code. Names and comments should follow my style strictly.
 * 
 * @author Fan Min [email protected].
 */
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

第 7 天: 矩阵元素相加

7.1 矩阵的赋值.
7.2 二重循环.

package basic;

import java.util.Arrays;

/**
 * This is the seventh code. Names and comments should follow my style strictly.
 * 
 * @author Fan Min [email protected].
 */
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.
	 * @param paraMatrix2 The second matrix. It should have the same size as
	 *                    the first one's.
	 * @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

}// Of class MatrixAddition

第 8 天: 矩阵相乘

8.1 三重循环是多数程序的极限.
8.2 非法输入检查是程序正常运行的基本保障. 如果检查所有的非法输入, 会导致大量代码行, 这在商业代码中是必须的.

package basic;

import java.util.Arrays;

/**
 * This is the eighth code. Names and comments should follow my style strictly.
 * 
 * @author Fan Min [email protected].
 */
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  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 j
		} // Of for i

		return resultMatrix;
	}// Of multiplication

	/**
	 *********************
	 * 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

第 9 天: while 语句

9.1 while 语句本质上比 for 更基础, 因此可以替代后者. 但 for 在很多时候更方便.
9.2 break 语句又出现了, 上次是在 switch 语句里. 都是表示跳出当前代码块.

package basic;

/**
 * This is the ninth code. Names and comments should follow my style strictly.
 * 
 * @author Fan Min [email protected].
 */
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

第 10天: 综合任务 1

学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 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.Arrays;
import java.util.Random;

/**
 * This is the tenth code, also the first task.
 * 
 * @author Fan Min [email protected].
 */
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

小结

本帖讨论了分支语句 (if, switch case), 循环语句 (for, while), 流程控制语句 (continue, break), 函数的使用. 这些内容和基本 C 语言的差不多. 数组的空间分配比 C 语言简单.
特别注意: 经常在 Eclipse 中使用鼠标右键 source -> format, 自动调整程序的格式.

你可能感兴趣的:(Java,程序设计基础,机器学习)