Java程序以查找矩阵中的最大数和最小数

时间:2020-01-09 10:35:33  来源:igfitidea点击:

在这篇文章中,我们将看到一个Java程序,用于查找矩阵或者2维数组中的最大和最小数。

Java程序

查找矩阵中最大和最小数量的逻辑如下:

最初将矩阵索引(0,0)处的元素分配给min和max变量。然后一次迭代矩阵一行,并首先将每个元素与max变量进行比较。

如果max变量小于当前元素,则将当前元素分配给max变量,否则将当前元素与min变量进行比较,如果min变量大于当前元素,则将当前元素分配给min元素。

public class MaxAndMin {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("Enter number of rows and columns in the matrix : ");
		int row = in.nextInt();
		int column = in.nextInt();
		// Prepare matrix
		System.out.print("Enter elements of Matrix : ");
		int matrix[][] = new int[row][column];
		for(int i = 0; i < row; i++){
			for(int j = 0; j < column; j++){
				matrix[i][j] = in.nextInt();
			}
		}
		System.out.println("Entered Matrix : " );
		for(int i = 0; i < row; i++){
			for(int j = 0; j < column; j++){
				System.out.print(" " +matrix[i][j]+"\t");
			}
			System.out.println();
		}
		// call method to find min and max in matrix
		findMinAndMax(matrix);
	}
 
	// Method to find maximum and minimum in matrix
	private static void findMinAndMax(int[][] matrix){     
		int maxNum = matrix[0][0];
		int minNum = matrix[0][0];
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				if(maxNum < matrix[i][j]){ 
					maxNum = matrix[i][j]; 
				} else if(minNum > matrix[i][j]){
					minNum = matrix[i][j];
				}
			}
		}
		System.out.println("Max number: " + maxNum + 
					" Min number: " + minNum);
	}
}

输出:

Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 3 6 12 34 19 5 32 16 7
Entered Matrix : 
 3	 6	 12	
 34	 19	 5	
 32	 16	 7	
Max number: 34 Min number: 3