问题描述
- java用编写一个4*4矩阵程序,并要求行列能够互换
-
各位大神帮帮忙,请编写一个程序,要求能够对一个4*4的矩阵进行行列互换,非常感谢!
解决方案
public static void main(String[] args) {
int[][] a = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int[][] b = new int[4][4];
int i, j;
System.out.println("源数组:");
for(i=0; i<4; i++){
for(j=0;j<4;j++){
System.out.print(a[i][j] + "t");
b[j][i]=a[i][j];
}
System.out.println();
}
System.out.println("转换后数组:");
for(i=0;i<4;i++) {
for(j=0;j<4;j++){
System.out.print(b[i][j] + "t");
}
System.out.println();
}
}
解决方案二:
public static void main(String[] args) {
List list=new ArrayList();
for (int i = 1; i <=22; i++) {
list.add(i);
}
for (int i = 0; i < list.size(); i++) {
int val=list.get(i);
System.out.print(val);
if(i%4!=3){
System.out.print("t");
}else{
System.out.println();
}
}
System.out.println();
System.out.println();
int n=list.size()/4+(list.size()%4==0?0:1);
System.out.println(n);
System.out.println();
System.out.println();
for (int i = 0; i <n; i++) {
for (int j = i; j < list.size(); j=j+n) {
System.out.print(list.get(j)+"t");
}
System.out.println();
}
}
时间: 2024-10-30 05:43:22