Java基本语法day2

日撸Java 三百行day2

学习来源:https://blog.csdn.net/minfanphd/article/details/116974889

基本for 语句

1、第一个程序,基本for 语句
1.1 循环语句是程序的核心.
1.2 算法的时间复杂度一般根据循环语句来计算.

package 日撸java三百行day1到day10;

/**
 * @time 2022/4/1
 * @author Liang Huang
 */

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=0; 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 ForStatement

矩阵元素相加

2、第二个程序,矩阵元素相加
2.1 矩阵的赋值.
2.2 二重循环.
2.3 求矩阵a的长度:a.length

package 日撸java三百行day1到day10;

import java.util.Arrays;

/**
 * @time 2022/4/1
 * @author Liang Huang
 */

public class MatrixAddition {

	/**
	 * ********
	 * The entrance of the program.
	 * 
	 * @param args not used now.
	 */
	
	
	public static void main(String[] args) {
		matrixElementSumTest();
		
		matrixAdditionTest();

	}//Of mian
	
	/**
	 *********
	 *Sum ehe 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

矩阵相乘

3、第三个程序,矩阵相乘
3.1 三重循环是多数程序的极限.
3.2 非法输入检查是程序正常运行的基本保障. 如果检查所有的非法输入, 会导致大量代码行, 这在商业代码中是必须的.

package 日撸java三百行day1到day10;

import java.util.Arrays;

/**
 * @time 2022/4/1
 * @author Liang Huang
 */

public class MatrixMultiplication {

	/**
	 * ********
	 * The entrance of the program.
	 * 
	 * @param args not used now.
	 */
	
	public static void main(String[] args) {
		
		matrixMultiplicationTest();
	}//Of main

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

while 语句

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

package 日撸java三百行day1到day10;

/**
 * @time 2022/4/1
 * @author Liang Huang
 */

public class WhileStatement {

	/**
	 * ********
	 * The entrance of the program.
	 * 
	 * @param args not used now.
	 */
	
	public static void main(String[] args) {
		
		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 exceediog " + 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

综合任务 1

5、第五个程序,综合任务 1
学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 0 行表示第 0 个学生的数学、语文、英语成绩。要求:

进行学生成绩的随机生成, 区间为 [50, 100].
找出成绩最好、最差的同学。但有挂科的同学不参加评比.
5.1 实际代码中,for 和 if 是最常见的, switch 和 while 使用少得多.
5.2 使用了 continue, 它是指继续跳过本次循环后面的代码,直接进入下一次循环. 而 break 是跳出整个循环体.

package 日撸java三百行day1到day10;

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


/**
 * @time 2022/4/1
 * @author Liang Huang
 */

public class Task1 {

	/**
	 * ********
	 * The entrance of the program.
	 * 
	 * @param args not used now.
	 */
	
	public static void main(String[] args) {
		
		task1();
	}//Of main
	
	public static void task1() {
		//Step 1. Generate the data with n students and m courses.
		//Set these values by yourself.
		int n = 12;
		int m = 3;
				
		int lowerBound = 50;//数据下界
		int upperBound = 100;//数据上界
		int threshold = 60;
				
		//Here wi 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
			
			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

java知识点小结:
1 求数组a的长度: a.length

2 随机数的生成。使用系统类Random.class。new一个Random对象tempRandom(Random tempRandom = new Random()), 再调用Random类里面生成随机数的方法。
2.1 生成随机整数:(1) tempRandom.nextInt(),随机生成一个没有上界的整数;(2)tempRandom.nextInt(n)生成一个在区间[0, n)的整数。
2.2 生成随机浮点数:(1) tempRandom.nextFloat(); (2) tempRandom.nextDouble()。范围在[0, 1]之间。
2.3 随机生成布尔类型: tempRandom.nextBoolean()。
2.4 随机生成长整型:tempRandom.nextLong()

3 打印数组的所有元素
方法1:通过一个for循环

for(int i=0; i<array.length; i++) {
			System.out.println(array[i]);
			
		}

方法2:通过Arrays类的toString()方法

System.out.println(Arrays.toString(array));

JDK提供的java.util.Arrays类,包含了常用的数组操作,方便日常开发。Arrays类包含了:排序,查找,填充,打印等常见的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别偷我的猪_09

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值