Java二维矩阵用户输入及90度旋转问题:元素显示不全排查
矩阵顺时针旋转问题的修复方案
问题根源
- 输出逻辑混乱:原代码里,打印原矩阵的循环每跑完一行就调用一次旋转方法,导致旋转后的矩阵被重复打印多次,输出顺序完全混乱。
- 硬编码限制矩阵尺寸:
rotate方法里用了固定的M=4,而且循环里i = M -4直接等于0,这意味着只会读取原矩阵第一行的元素,完全没考虑用户输入的实际行列数,自然只能显示少量内容。 - 旋转逻辑错误:顺时针转90度的正确逻辑是按原矩阵的列从左到右遍历,每一列从下到上取元素,原代码的循环范围完全不符合这个逻辑。
修正后的代码
import java.util.Scanner; public class MatrixRotation { public static void main(String args[]) { int m, n, i, j; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of rows: "); m = sc.nextInt(); System.out.print("Enter the number of columns: "); n = sc.nextInt(); int[][] array = new int[m][n]; System.out.println("Enter the elements of the array: "); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { array[i][j] = sc.nextInt(); } } // 打印原矩阵 System.out.println("Elements of the array are: "); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } // 打印旋转后的矩阵 System.out.println("The matrix after being rotated 90 degrees clockwise: "); rotate(array, m, n); } // 动态适配用户输入的行列数 static void rotate(int[][] arr, int m, int n) { // 顺时针90度旋转逻辑:按列遍历,从下到上取元素 for (int j = 0; j < n; j++) { for (int i = m - 1; i >= 0; i--) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
关键修正点
- 把旋转方法的调用移到原矩阵打印完成之后,避免重复输出。
- 给
rotate方法传入用户输入的行数m和列数n,彻底去掉硬编码的固定尺寸限制。 - 修正旋转遍历逻辑:外层循环遍历原矩阵的每一列,内层循环从最后一行到第一行依次取元素,完美实现顺时针90度旋转的效果。
内容的提问来源于stack exchange,提问作者Erik Ivarsson
相关产品推荐
相关产品推荐

