矩阵的交换列
我制作了此代码,以便与3x3
矩阵中的第一列和最后一列交换位置。我需要使用2种不同的方法,一种打印原始矩阵和一个打印修改的矩阵。
我能够做第一个,但是第二个问题有问题。
public class SwapMatrix {
public static void main(String[] args) {
int matrix [][] =
{{3, 4, 5},
{7, 8, 9},
{1, 2, 3}};
System.out.println("\n Normal Matrix:");
print(matrix);
//int matrixModified [][] = swap(matrix);
//System.out.println("\n New Matrix:");
//print(matrixModified);
}
public static void print (int matrix[][]){
for (int i=0; i<matriz.length; i++){
for (int j=0; j<matrix[0].length; j++){
System.out.print(matriz [i][j]+ "\t");
}
System.out.println();
}
}
}
I made this code in order to swap places with the first column and the last column in a 3x3
Matrix. I would need to use 2 different methods, one to print the original matrix and one to print the modified matrix.
I was able to do the first one, but I have problems with the second.
public class SwapMatrix {
public static void main(String[] args) {
int matrix [][] =
{{3, 4, 5},
{7, 8, 9},
{1, 2, 3}};
System.out.println("\n Normal Matrix:");
print(matrix);
//int matrixModified [][] = swap(matrix);
//System.out.println("\n New Matrix:");
//print(matrixModified);
}
public static void print (int matrix[][]){
for (int i=0; i<matriz.length; i++){
for (int j=0; j<matrix[0].length; j++){
System.out.print(matriz [i][j]+ "\t");
}
System.out.println();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想向后打印矩阵,那么您要做的就是计数循环中的倒数。
If you want to print the matrix backwards, all you have to do is to count reverse in your loop.
您可以通过两种方式实现
swap()
方法:由创建一个新矩阵,或者通过交换给定矩阵的列到位 。1。首先,您需要创建一个新矩阵。
然后用嵌套
迭代
循环以反向顺序分配新矩阵中每个 row 的元素。即位置 row 的第一个元素的值0
将分配给位置矩阵[0] .length -1
的元素。反之亦然(所有其他元素)。2。要将给定的矩阵交换到位,您需要为循环创建一个嵌套
。内部循环中的迭代应仅发生,直到代表每一行的数组的中间(很重要),如果“在一行元素的完整长度上迭代”将被交换两次,并且矩阵将保持相同)。
sidenote: ,尽管
int matrix [] [] []
是一种从 c 语言继承的有效语法,但它不是一个使用它的好练习是因为该符号将两个完全不同的概念混合在一起:a 变量名称和a type 。定义数组int [] []矩阵
的首选方法。You can implement the
swap()
method in two ways: either by creating a new matrix or by swapping the columns of the given matrix in place.1. Firstly, you need to create a new matrix.
And then iterate over it with a nested
for
loop assigning the elements of each row in the new matrix in reversed order. I.e. the value of the first element of the row at position0
would be assigned to the element at positionmatrix[0].length - 1
and vice versa (the same hold true for all other elements).2. To swap the given matrix in place, you need to create a nested
for
loop. Iteration in the inner loop should happen only until the middle of the array representing each row (that's important, if'll iterate over the full length of a row elements will get swapped twice and the matrix will remain the same).Sidenote: although
int matrix[][]
is a valid syntax inherited from the C language, it's not a good practice to use it because this notation mixes two completely different notions: a variable name and a type. The preferred way to define an arrayint[][] matrix
.