我需要编写一个程序,从用户那里获取数字 n 并创建一个向上计数的 nxn 矩阵,然后我需要转置它。我尝试了多种编码方法,但没有任何显示正确。
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args)
{
//Variables
int size;
int value;
//Scanner
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("Enter the size of the Square Matrix: ");
size = input.nextInt();
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = i+j;
System.out.print(value);
}
}
}
}
我目前得到的结果是:
Enter the size of the Square Matrix:
3
123
234
345
我需要它看起来更像这样:
Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
最佳答案
nxn矩阵向上计数为
for(int i=0; i<size; i++) {
System.out.println();
for(int j=1; j<=size; j++) {
value = j + i*size;
System.out.print(value);
}
}
转座是
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = j*size + i;
System.out.print(value);
}
}
关于java - 打印方阵并使用 Java 对其进行转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863881/