提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
这里是JAVA自学与了解的同步笔记与记录,如有问题欢迎指正说明
I have loved the stars too fondly to be fearful of the night.
Day01——从“Hello World”开始吧
public class HelloWould {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello Would!");
}// Of main
}// Of class HelloWould
Day02——基本算术操作
练习:四则运算
public class math {
public static void main(String[] args) {
// TODO Auto-generated method stub
int tempFirstInt = 15,
tempSecondInt = 4,
tempResultInt;
double tempFirstDouble= 1.2,
tempSecondDouble = 3.5,
tempResultDouble;
// +
tempResultInt = tempFirstInt + tempSecondInt;
tempResultDouble = tempFirstDouble + tempSecondDouble;
System.out.println(tempFirstInt + " + " + tempSecondInt + " = " + tempResultInt);
System.out.println(tempFirstDouble + " + " + tempSecondDouble + " = " + tempResultDouble);
// -
tempResultInt = tempFirstInt - tempSecondInt;
tempResultDouble = tempFirstDouble - tempSecondDouble;
System.out.println(tempFirstInt + " - " + tempSecondInt + " = " + tempResultInt);
System.out.println(tempFirstDouble + " - " + tempSecondDouble + " = " + tempResultDouble);
// *(乘)
tempResultInt = tempFirstInt * tempSecondInt;
tempResultDouble = tempFirstDouble * tempSecondDouble;
System.out.println(tempFirstInt + " * " + tempSecondInt + " = " + tempResultInt);
System.out.println(tempFirstDouble + " * " + tempSecondDouble + " = " + tempResultDouble);
// /(除)
tempResultInt = tempFirstInt / tempSecondInt;
tempResultDouble = tempFirstDouble / tempSecondDouble;
System.out.println(tempFirstInt + " / " + tempSecondInt + " = " + tempResultInt);
System.out.println(tempFirstDouble + " / " + tempSecondDouble + " = " + tempResultDouble);
// %(取余)
tempResultInt = tempFirstInt % tempSecondInt;
System.out.println(tempFirstInt + " % " + tempSecondInt + " = " + tempResultInt);
}//Of main
}//Of class math
运行结果
Day03——基本if语句
练习:求绝对值
public class HelloWould {
public static void main(String[] args) {
// TODO Auto-generated method stub
int tempNumber1 = 6;
System.out.println("The absolute value of " + tempNumber1 + " is " + abs(tempNumber1));
int tempNumber2 = -8;
System.out.println("The absolute value of " + tempNumber2 + " is " + abs(tempNumber2));
}// Of main
public static int abs(int paraValue) {
if (paraValue >= 0) {
return paraValue;
} else {
return -paraValue;
} // Of if
}// Of abs
}
运行结果
小结
if-else语句在Java编程中较为常用,是常见的多分支语句。上段程序用于求一个整型数的绝对值,取绝对值的部分单独作为一个静态方法,通过引用方法传入实参,可让方法返回一个值,这个值即为所给数的绝对值。
Day04——if语句嵌套
练习:闰年的计算
//闰年的判断条件:可被4整除但不能同时被100整除,或者能被400整除
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.");
// Test isLeapYearV2
System.out.println("Now use the second version.");
System.out.print("" + tempYear + " is ");
if (!isLeapYearV2(tempYear)) {
System.out.print("NOT ");
} // Of if
System.out.println("a leap year.");
//下面是包含双分支if—-else的方法
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
//下面是包含多分支if-else的方法
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
}
小结
1.在一个分支中又完整的嵌套了另一个完整的分支结构,里面的分支结构称为内层分支,外面的分支结构称为外层分支。
2.嵌套最好不要超过3层,否则可读性差
Day05——基本switch语句
练习 : 判断分数的对应等级
package basic;
/**
* This is the fifth code. Names and comments should follow my style strictly.
*/
public class SwitchStatement {
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
运行结果
小结
1.switch(表达式)中,表达式的数据类型应该和case后的常量类型一致,或者是可以自动转换成可以相互比较的类型,如常量为int,而输入是字符。
2.switch(表达式)中,表达式的返回值必须是:(byte,short,int,char,String,enum(枚举))
3.case子句中的值必须是常量,而不能是变量
4.可以没有default
5.break语句执行后跳出该switch。如果没有break,则程序会顺序执行到switch结尾
Day06——基本for语句
练习 :1累加到N
public class e_for {
public static void main(String[] args) {
// TODO Auto-generated method stub
forStatementTest();
}// of main
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
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
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
运行结果
· 补充:增强型For循环
1.形式如下
for(声明语句 : 表达式)
{
//代码句子
}
2.声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配(即与表达式中的数据结构集合中的每个子项的类型匹配)。其作用域限定在循环语句块,其值与此时数组元素的值相等。
表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
3.具体用法
public class Test {
public static void main(String[] args) {
int[] numbers = { 10, 20, 30, 40, 50 }; // Create a int array
for (int x : numbers) { // Get the elements in the array in order
System.out.print(x);
System.out.print(",");
}
System.out.print("\n");
String[] names = { "James", "Larry", "Tom", "Lacy" }; // Create a string array
for (String name : names) {
System.out.print(name);
System.out.print(",");
}
}
}
4.运行结果
5.需注意:
for(val : array)的遍历之下的每个val值是仅仅可读的,但是不可写,val只能用来获取而无法通过修改val来修改array对于中的数据。即读取的val不是这个array中那个对应数的地址,因此修改val无法改动到array。
小结
1.尝试使用主方法与一般方法分离的模式编程,main函数只负责简单的驱动作用。优点:能使主方法代码规模更小,看起来更简洁,主方法与一般方法的引用和被引用关系更明确,利于提高工作效率。
2.循环条件是能返回一个布尔值的表达式。
3.for(; 循环条件 ;)中的初始化和变量迭代可以写在其他地方,但是两边的分号不能省略。
4. 循环的初始化可以有多条初始化语句,但要求数据类型一致,并且中间用逗号隔开。
Day07——矩阵:运动的描述
1.动态创建:
//一维数组
dataType[] arrayRefVar = new dataType[arraySize];
//1.使用dataType[arraySize]创建了一个数组
//2.把创建的数组的引用赋值给变量 arrayRefVar
//二维数组
dataType[][] arrayRefVar = new dataType[arrayHeight][arrayWidth];
2.静态创建:
dataType[10] arrayRefVar1;
dataType[10][20] arrayRefVar1;
double[] arrayRefVar2 = {1.2, 2.3, 3.4};
练习 :矩阵求和
import java.util.Arrays;
public class e_array {
//主方法负责驱动函数
public static void main(String args[]) {
matrixElementSumTest();
matrixAdditionTest();
}// Of main
//函数功能:将传入的二维数组内的每一个元素求和,并返回这个和
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.
*********************
*/
// 通过两个for循环嵌套使用,给矩阵tempMatrix赋初值
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 sum is: " + matrixElementSum(tempMatrix) + "\r\n");
}// Of matrixElementSumTest
//两个for循环嵌套,实现两个矩阵的相加,即为其对应元素的相加
public static int[][] matrixAddition(int[][] paraMatrix1, int[][] paraMatrix2) {
if (paraMatrix1.length != paraMatrix2.length || paraMatrix1[0].length != paraMatrix2[0].length) {
System.out.println("Error! Two matrixs must have same height and width! ");
}
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 matroxAddition
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 matrixAddtionTest
}// Of class MatrixAddtion
运行结果
注意:
1.paraMatrix.length 表示矩阵的宽,即行数
2.paraMatrix[0].length 表示矩阵第一行的长度
3.具体遍历的话,基本所有语言的二维存储都是采用行优先的存储,而普遍的遍历都是先行后列的遍历思想
·补充说明array类
1.排序数组的方法
public static void sort(Object[] a)
对指定对象数组根据其元素的自然顺序进行升序排列。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。
Arrays.sort(tempArrays); //正序排tempArrays
Arrays.sort(tempArrays,Collections.reverseOrder()); //逆序排tempArrays
Arrays.sort(tempArrays, i, j);//正序对tempArrays的i到j位置进行排序
2.填充操作
public static void fill(int[] a, int val)
将指定的 int 值分配给指定 int 型数组指定范围中的每个元素。
3.快速遍历
Arrays.toString(Object[] array)
功能:返回数组的字符串形式
int[] nums = {2,5,0,4,1,-10};
System.out.println(Arrays.toString(nums));
/*
* 结果:[2, 5, 0, 4, 1, -10]
*/
Arrays.deepToString(Object[][] arrays)
功能:返回多维数组的字符串形式
int[][] nums = {{1,2},{3,4}};
System.out.println(Arrays.deepToString(nums));
/*
* 结果:[[1, 2], [3, 4]]
*/
Day08——矩阵的乘法
练习:矩阵相乘
目标:1.可以判断两个矩阵是否能相乘,即是否符合第一个矩阵的列数等于第二个矩阵的行数
2.创建矩阵后用for循环给矩阵赋初值
3.三个for循环嵌套使用,第一层拿到A矩阵的逐行,第二层拿到B矩阵的逐列,最内层实现
求和
package basic;
import java.util.Arrays;
public class MatrixMultiplication {
public static void main(String args[]) {
matrixMultiplicationTest();
}// Of main
//矩阵相乘实现方法
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.
*********************
*/
//初始化矩阵1
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));
//初始化矩阵2
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 + 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 matrixMultiplication
运行结果
小结
1.\r\n相当于硬回车,会另起一行。\n\r会在中间空出一行后在另起一行
Day09——whlie语句
练习:
package good_better;
import java.util.PrimitiveIterator.OfDouble;
/**
* The usage of the sth.
*
* @author Wanxiang Luo 2858442831@qq.com
*/
public class e_while {
/**
*
*********************
* The entrance of the program.
*
* @param args
*********************
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
whileStatementTest();
}// of main
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\n second 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 whlieStatementTest
}
运行结果
小结
1.方法1每次循环判断()内的循环条件是否为真,若为true,则执行一次循环体。方法2的循环条件一直为真,循环体内设置if语句进行判断,一旦满足条件则即刻跳出当前while循环。
2.while 语句本质上比 for 更基础, 因此可以替代后者. 但 for 在很多时候更方便.
Day10——综合任务
1.任务要求
学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 0 行表示第 0 个学生的数学、语文、英语成绩。要求:
1.进行学生成绩的随机生成, 区间为 [50, 100].
2.找出成绩最好、最差的同学。但有挂科的同学不参加评比.
2.对任务的分析
1.每个学生的科目都是三科,故可将数据放入一个m*3的矩阵。
2.通过一个数组来统计每个学生的成绩总和,得到最低成绩和最高成绩
3.运用Java提供的Random库解随机数生成的问题:
java Random.nextInt()方法
public int nextInt(int n)
该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n
对于本次任务还需注意:
1.随机数生成区间前闭后开,故无法生成n
2.指定[a,b)区间的生成:a + temRandom.nextInt(b - a);
3.数据是整型不是浮点型
3.代码实现
package good_better;
import java.util.Arrays;
import java.util.Random;
/**
*The usage of the sth.
*
* @author Wanxiang Luo 2858442831@qq.com
*/
public class randomData {
/**
*
*********************
*The entrance of the program.
*
* @param args
*********************
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
task1();
}
public static void task1() {
// Step 1. Generate the date with n student and m course.
// Set these value by yourself.
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 101;
int threshold = 60;
// Here we have to use an object to generate random numbers
Random temRandom = 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 + temRandom.nextInt(upperBound - lowerBound);
//生成50到101间的随机数
} // 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;
//有挂科的同学不参与统计,以0代替
} // 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 Statememt 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 student 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 student have failed.");
} else {
System.out.println("The worst Student is No." + tempWorstIndex + " with scores: "
+ Arrays.toString(data[tempWorstIndex]));
} // Of if
}// Of task1
}
运行结果
测试了两组不同的结果
小结
1.step 3中不能用if-else结构囊括求极大值和求极小值方案,因为学生的成绩可能同时是最高分和最低分。
2.step 3中使用了编程中常见得不能再常见的求极值方案——通过给预求极值设定一个反方向的最极限值(说人话就是给最大值设定一个能取的最小值为初始值,给最小值设定一个能取的最大值为初始值)
3.前十天进行了基本语法的学习,可以看出每日的难度和代码长度都在逐步递增。下一步的学习任务,是对数据结构的复习和加深认识。每一次的学习都是点亮一个又一个的知识点,但不要忘了还需将这些知识点串联起来,才能形成更高效有序的’网’。以后的学习,我会拆分较难理解的方面成一个个更小的知识点,逐步理解拾级而上。