Java程序在矩阵的每一行中查找最大元素

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

在本文中,我们将看到一个Java程序,该程序可以在矩阵的每一行中找到最大的元素。

例如,如果有下面给出的矩阵

10  8   6
0   13  7
17  3   15

然后,程序应按如下所示找到矩阵中每一行的最大元素:

第1行中的最大元素= 10
第2行中的最大元素= 13
第3行中的最大元素= 17

Java程序–在矩阵的每一行中查找max元素

public class MatrixMaxElement {

	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 col = in.nextInt();
		// Prepare matrix
		int[][] matrix = prepareMatrix(row, col);
		findMaxInEachRow(matrix);
		in.close();
	}
	// Method to enter matrix elements
	private static int[][] prepareMatrix(int row, int column){
		Scanner sc = new Scanner(System.in);
		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] = sc.nextInt();
			}
		}
		sc.close();
		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();
		}
		return matrix;
	}
	// Method to find the maximum element in each row
	private static void findMaxInEachRow(int[][] matrix){
		int[] tempArray = new int[matrix.length];
		for (int i = 0; i < matrix.length; i++) {
			// Start with first element of the row
			int max = matrix[i][0];
			for (int j = 0; j < matrix[i].length; j++) {
				if(max < matrix[i][j]){
					max = matrix[i][j];
				}
				tempArray[i] = max;
			}         
		}        
		// Displaying max elements
		for (int i = 0; i < tempArray.length; i++) {
			System.out.println("Maximum element in row-" + (i + 1) + " = " + tempArray[i]);
		}
	}
}

输出:

Enter number of rows and columns in the matrix: 3 3
Enter elements of Matrix : 10 8 6
0 13 7
17 3 15
Entered Matrix : 
 10	 8	 6	
 0	 13	 7	
 17	 3	 15	
Maximum element in row-1 = 10
Maximum element in row-2 = 13
Maximum element in row-3 = 17