JavaDay2

学习来源:日撸 Java 三百行(01-10天,基本语法)_闵帆的博客-CSDN博客

一、循环语句

1. for语句

        程序执行for循环时,先执行循环的初始化语句,初始化语句只在循环开始前执行一次。每次执行循环体前,都先计算循环条件的值,如果循环条件返回true,则执行循环体,循环体执行结束后执行循环迭代语句。

2. for语句的基本应用——从1到n的累加

代码如下

package JavaDay2;
/**
 * @author Kexiong Wang.
 *
 * @date 2022年4月13日.
 */
public class ForStatement {

    /**
     *********************
     * 程序入口
     *
     * @param args 暂未使用
     *********************
     */
    public static void main(String args[]) {
        forStatementTest();
    }//Of main

    /**
     *********************
     * 数据测试
     *********************
     */
    public static void forStatementTest() {
        //加到最大的数
        int tempNum = 8;
        System.out.println("1 add to " + tempNum + " is: " + addToNum(tempNum));

        tempNum = 0;
        System.out.println("1 add to " + tempNum + " is: " + addToNum(tempNum));

        //每次增加的步长
        int tempStepLength = 1;
        tempNum = 10;
        System.out.println("1 add to " + tempNum + " with step length " + tempStepLength + " is: "
                + addToNumWithStepLength(tempNum, tempStepLength));

        tempStepLength = 2;
        System.out.println("1 add to " + tempNum + " with step length " + tempStepLength + " is: "
                + addToNumWithStepLength(tempNum, tempStepLength));
    }//Of forStatementTest

    /**
     *********************
     * 从1加到n
     *
     * @param paraNum 加到的最大值n
     * @return        累加的结果
     *********************
     */
    public static int addToNum(int paraNum) {
        //累加的结果
        int resultSum = 0;

        for (int i = 1; i <= paraNum; i++) {
            resultSum += i;
        } //Of for i

        return resultSum;
    }//Of addToNum

    /**
     *********************
     * 跳步累加
     *
     * @param paraNum          累加的最大值
     * @param paraStepLength   跳步步长
     * @return                 总和
     *********************
     */
    public static int addToNumWithStepLength(int paraNum, int paraStepLength) {
        //跳步累加的结果
        int resultSum = 0;

        for (int i = 1; i <= paraNum; i += paraStepLength) {
            resultSum += i;
        } //Of for i

        return resultSum;
    }//Of addToNumWithStepLength

}//Of class ForStatement

运行结果

3. for语句的中阶应用——二重循环之矩阵元素相加

代码如下

package JavaDay2;

import java.util.Arrays;

/**
 * @author Kexiong Wang
 *
 * @date 2022年4月13日
 */
public class MatrixAddition {

    /**
     *********************
     * 程序如口
     *
     * @param args 暂未使用
     *********************
     */
    public static void main(String args[]) {
        matrixElementSumTest();

        matrixAddTest();
    }//Of main

    /**
     *********************
     * 求矩阵所有元素之和
     *
     * @param paraMatrix  传入的矩阵
     * @return            所有矩阵元素之和
     *********************
     */
    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

    /**
     *********************
     * 矩阵元素赋值并求和
     *********************
     */
    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

    /**
     *********************
     * 两个矩阵相加
     *
     * @param paraMatrix1  矩阵1
     * @param paraMatrix2  矩阵2(要求为矩阵1的同型矩阵)
     * @return             两个矩阵相加的结果
     *********************
     */
    public static int[][] matrixAdd(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 matrixAdd

    /**
     *********************
     * 矩阵相加的方法测试
     *********************
     */
    public static void matrixAddTest() {
        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 = matrixAdd(tempMatrix, tempMatrix);
        System.out.println("The new matrix is: \r\n" + Arrays.deepToString(tempNewMatrix));
    }//Of matrixAddTest

}//Of class matrixAddition

运行结果

4. for语句使用的强化练习——三重循环之矩阵相乘

代码如下

package JavaDay2;

import java.util.Arrays;

/**
 * @author Kexiong Wang
 *
 * @date 2022年4月13日
 */
public class MatrixMultiplication {

    /**
     *********************
     * 程序入口
     *
     * @param args 暂未使用
     *********************
     */
    public static void main(String args[]) {
        matrixMulTest();
    }//Of main

    /**
     *********************
     * 矩阵相乘,矩阵1和矩阵2需满足矩阵相乘条件
     *
     * @param paraFirstMatrix   矩阵1
     * @param paraSecondMatrix  矩阵2
     * @return                  相乘结果
     *********************
     */
    public static int[][] matrixMul(int[][] paraFirstMatrix, int[][] paraSecondMatrix) {
        //矩阵1行数
        int m = paraFirstMatrix.length;
        //矩阵1列数
        int n = paraFirstMatrix[0].length;
        //矩阵2列数
        int p = paraSecondMatrix[0].length;

        //判断两个矩阵能否相乘
        if (paraSecondMatrix.length != n) {
            System.out.println("The two matrices cannot be multiplied.");
            return null;
        }//Of if

        //矩阵相乘
        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 matrixMul

    /**
     *********************
     * 矩阵相称方法测试
     *********************
     */
    public static void matrixMulTest() {
        //第一个矩阵
        int[][] tempMatrix1 = new int[2][3];
        for (int i = 0; i < tempMatrix1.length; i++) {
            for (int j = 0; j < tempMatrix1[0].length; j++) {
                tempMatrix1[i][j] = i + j;
            }//Of for j
        }//Of for i
        System.out.println("The first matrix is: \r\n" + Arrays.deepToString(tempMatrix1));
        
        //第二个矩阵
        int[][] tempMatrix2 = new int[3][2];
        for (int i = 0; i < tempMatrix2.length; i++) {
            for (int j = 0; j < tempMatrix2[0].length; j++) {
                tempMatrix2[i][j] = i * 10 + j;
            }//Of for j
        }//Of for i
        System.out.println("The second matrix is: \r\n" + Arrays.deepToString(tempMatrix2));
        
        //矩阵1和矩阵2相乘
        int[][] tempMatrix3 = matrixMul(tempMatrix1, tempMatrix2);
        System.out.println("The third matrix is: \r\n" + Arrays.deepToString(tempMatrix3));
        
        //矩阵1和自己相乘
        System.out.println("Trying to multiply the first matrix with itself.\r\n");
        tempMatrix3 = matrixMul(tempMatrix1, tempMatrix1);
        System.out.println("The result matrix is: \r\n" + Arrays.deepToString(tempMatrix3));
    }//Of matrixMulTest

}//Of class MatrixMultiplication

运行结果

5. while语句

while循环每次执行循环体之前,先对循环条件求值,如果为true,则运行循环体部分。当循环体成功执行完成时,while循环才会执行迭代语句。

6. while语句的简单应用

代码如下

package JavaDay2;

/**
 * @author Kexiong Wang
 *
 * @date 2022年4月13日
 */
public class WhileStatement {

    /**
     *********************
     * 程序入口
     *
     * @param args 暂未使用
     *********************
     */
    public static void main(String args[]) {
        whileStatementTest();
    }//Of main

    /**
     *********************
     * 求不超过给定值的最大累加和
     *********************
     */
    public static void whileStatementTest() {
        //给定的最大值
        int tempMax = 100;
        //累加数
        int tempValue = 0;
        //累加的和
        int tempSum = 0;

        //方案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);

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

运行结果

二、综合练习

        现有一存放学生成绩的矩阵,行表示学生,列表示科目,矩阵中的每行元素代表学生的数学、语文、英语成绩。

1. 要求

        1.1在矩阵中随机生成学生的成绩,成绩范围为[50,100]。

        1.2分别找出成绩最好和最差的学生,但不包括有挂科的同学。

2. 代码如下

package JavaDay2;

import java.util.Arrays;
import java.util.Random;

/**
 * @author Kexiong Wang
 *
 * @date 2022年4月13日
 */
public class TaskDay2 {

    /**
     *********************
     * 程序入口
     *
     * @param args 暂未使用
     *********************
     */
    public static void main(String args[]) {
        task();
    }//Of main

    /**
     *********************
     * 方法测试
     *********************
     */
    public static void task() {
        //生成学生的数据
        //学生个数
        int n = 5;
        //学科数
        int m = 3;
        //随机生成学生成绩的范围
        int lowerBound = 50;
        int upperBound = 100;
        //及格线
        int threshold = 60;

        //随机生成学生成绩
        Random tempRandom = new Random();
        int[][] score = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                score[i][j] = lowerBound + tempRandom.nextInt(upperBound - lowerBound);
            }//Of for j
        }//Of for i

        System.out.println("The score is:\r\n" + Arrays.deepToString(score));

        //计算每个学生的总分
        int[] totalScore = new int[n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                //有不及格学科的同学不计入评比
                if (score[i][j] < threshold) {
                    totalScore[i] = 0;
                    break;
                }//Of if

                totalScore[i] += score[i][j];
            }//Of for j
        }//Of for i

        System.out.println("The total scores are:\r\n" + Arrays.toString(totalScore));

        //筛选成最好和最差的学生
        int tempBestIndex = -1;
        int tempWorstIndex = -1;

        int tempBestScore = 0;
        int tempWorstScore = m * upperBound + 1;

        for (int i = 0; i < n; i++) {
            //忽略有挂科的学生
            if (totalScore[i] == 0) {
                continue;
            }//Of if

            if (tempBestScore < totalScore[i]) {
                tempBestScore = totalScore[i];
                tempBestIndex = i;
            }//Of if

            if (tempWorstScore > totalScore[i]) {
                tempWorstScore = totalScore[i];
                tempWorstIndex = i;
            }//Of if
        }//Of for i

        //输出结果
        //成绩最好的学生
        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(score[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(score[tempWorstIndex]));
        }//Of if
    }//Of task
}//Of class TaskDay2

3. 运行结果

 三、总结

        1. 主要学习了循环语句中的for语句和while语句,实践练习for循环语句的单层、双层以及三层嵌套循环的使用。其中单层及双层循环使用场景较多,三层循环很少使用,因为在三层循环中,循环体语句的执行次数相较于前两种循环太大,可能会导致时间复杂度太高、程序运行效率大大降低。

        2. 使用break和continue可以跳出循环。但continue是指跳过本次循环,进入下一轮的循环判断条件语句。break则是跳出当前循环体。

        3. 同样return也可以跳出循环,但return关键字并不是专门用于结束循环的,它的功能是结束方法,循环自然也随之结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值