日撸 java三百行 day1

说明:

万事开头Hello World!目前是在职准备去读研,虽然目前自主使用编译语言基本是python,java是大二时候学的,已经遗忘很多了,java配置环境相对于python来说较复杂一些,还好之前工作的这台电脑有配置,可以先拿来练手。 

闵老师的文章链接:日撸 Java 三百行(总述)-CSDN博客

目录

1、Hello World

2、基本算术操作

3、基本 if 语句

4、闰年的计算

5、基本Switch语句

6、基本for 语句

7、矩阵元素相加

8、矩阵相乘


 1、Hello World

相较于c和python,java的打印长度还是比较长的,所以使用了sout+回车快速输入打印语句;然后就是在编译时使用快捷shift+F10时遇到的问题,shift+F10会直接运行你最后一次编译运行的java文件,我是直接修改的java文件名,然后shift+F10编译的话文件名是不同步的,就会导致报错,提示以下信息

原因: java.lang.ClassNotFoundException: Main

因为改名后根据之前编译运行的文件名来找对应的文件找不到的,所以在新建的java文件中还是使用ctrl+shift+F10来快捷编译运行,而不是ctrl+F10

package basic;

/**
 * This is the first code. Names and comments should follow my style strictly.
 * @author Fan Min minfanphd@163.com. 
 */
public class HelloWorld {

	public static void main(String args[]) {
		System.out.println("Hello, world!");
	}//Of main
}//Of class HelloWorld

2、基本算术操作

这里主要包含了整形(int)以及双精度类型(double)分别对应的加、除以及整形的取余,之前在c语言刷题当中有遇到过很多需要类型转换以及算术操作,其实也会绕晕,具体操作当中先理解了我需要以什么类型存储结果,然后基本算术逻辑,再去依次尝试解决。

这道练手的代码另一个点是打印,python,c,java三者打印方式均有差异,这段打印代码也把我再纠回了java中。

package basic;

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;
        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 + " = " + tempResultDouble);

    }
}

3、基本 if 语句

1、这里其实主要包含两种方式,一种方式是通过判断变量值是大于0还是小于0,即是正是负,是负的话则直接通过在变量名前加负号将其转正,第二种方式是通过设置绝对值函数,函数的逻辑和第一种方式一致,如果有多个数的话使用函数会提高代码的复用性。
2、第二点值得一提的是关于注释的问题,我有一个不好的习惯就是不爱打注释,或者注释的乱七八糟,这点在代码量比较小的时候还是不会有什么大影响的,但是当代码量上去后,有的时候难免会忘记这个函数是代表什么,尽管有的部分有了注释,但是注释内容又不完善,也会稀里糊涂的,再一个是比如这个代码在短期内跑没问题,但是突然有一天出了bug,就会发现有些逻辑忘记了,还要再去依次检查,无法定位检查。所以注释的规范性还是很重要的,还是需要多加联系。

package basic;

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
        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));
    }

    /**
     * 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、闰年的计算

闰年的计算规则不多赘述,这里是通过每次修改变量的数值,通过函数和循环判断其是否是闰年,不是闰年的话则进入循环判断的结果打印NOT

package basic;

/**
 * @author Fan Min minfanphd@163.com.
 **/
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.println("" + tempYear + " is ");
        if(!isLeapYear(tempYear)){
            System.out.println("NOT ");
        }//of if
        System.out.println("a leap year.");

        tempYear = 2000;

        System.out.println("" + tempYear + " is ");
        if(!isLeapYear(tempYear)){
            System.out.println("NOT ");
        }// of if
        System.out.println("a leap year.");

        tempYear = 2100;

        System.out.println("" + tempYear + " is ");
        if(!isLeapYear(tempYear)){
            System.out.println("NOT ");
        }//of if
        System.out.println("a leap year.");

        tempYear = 2004;

        System.out.println("" + tempYear + " is ");
        if(!isLeapYear(tempYear)){
            System.out.println("NOT ");
        }//of if
        System.out.println("a leap year.");

        //Test isLeapYearV2
        System.out.println("Now use the second version.");
        tempYear = 2021;

        System.out.println("" + tempYear + " is ");
        if(!isLeapYearV2(tempYear)){
            System.out.println("NOT ");
        }//of if
        System.out.println("a leap year.");

        tempYear = 2000;

        System.out.println("" + tempYear + " is ");
        if(!isLeapYearV2(tempYear)){
            System.out.println("NOT ");
        }//of if
        System.out.println("a leap year.");

        tempYear = 2100;

        System.out.println("" + tempYear + " is ");
        if(!isLeapYearV2(tempYear)){
            System.out.println("NOT ");
        }//of if
        System.out.println("a leap year.");

        tempYear = 2004;

        System.out.println("" + tempYear + " is ");
        if(!isLeapYearV2(tempYear)){
            System.out.println("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 whit 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语句

这里和之前不同的是主函数只有调用函数的一条语句,函数当中调用另一个函数,判断函数中对传入数据进行判断,根据分数打出对应的等级,最后将结果传回测试函数,在测试函数中输出。

Switch函数之前大多是用于判断的结果值较少一些,所以这里有一个点是在跟着敲的过程中发现的,是好几条case语句是没有执行语句以及break的,在最后一条case语句后跟了一个结果语句以及break,通过搜索发现,如果满足case条件,就会一直执行至遇到break,所以可以将这些case对应的值都视为同一个结果。

package basic;

/**
 * @author Fan Min minfanphd@163.com.
 **/
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';
            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 语句

这里值得注意的是“步长”的设置,通过循环变量循环一次加对应的步长来实现跳步遍历

package basic;

/**
 * @author Fan Min minfanphd@163.com.
 **/
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 +=1;
        }//of for i

        return resultSum;
    }//of addToNWithStepLength
}//of class ForStatement

 7、矩阵元素相加

 此练习主要分两个部分,均是相加求和,但是相加的对象不同:

1、第一种相加是二维数组内所有元素相加求和;

2、第二种相加是该二维数组对应元素相加,因为只初始化了一个二维数组,所以对应数字相同,求和后的结果可以理解为每个元素乘2.

这里值得注意的是打印部分的\r\n,先打印\r\n前的内容,然后换行打印\r\n后的内容。

此练习导入了Arrays包,使用了deepToString函数,目的是为了将二维数组转换为字符串形式打印出来。与之对应的是toString函数,效果相同,但是针对的是一维数组。

package basic;

import java.util.Arrays;
/**
 * @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));
    }//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 atrixAdditionTest
}// of class MatrixAddition

 8、矩阵相乘

这里主要需要理解的是三重循环,最外层循环是定位到某行,第二层是定位到行中的某一列,即该行的某一个值,第三层是为了计算定位到行中某一个值的数。

package basic;

import java.util.Arrays;
/**
 * @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

    /**
     * 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; //m=2
        int n = paraFirstMatrix[0].length; //n=3
        int p = paraSecondMatrix[0].length;//p=2

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

 今日学习主要是基础的语法,算术操作、循环、判断、Switch-case、数组的相关操作,补充了java的基础知识,包括Switch-case的默认执行、注释的规范性、打印的基础等等,学习路漫漫,如有解释不正确或补充的地方请指正!

  • 21
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值