编写一个Java程序,形成以下形式的二维数组,并输出。

如题所述

import java.util.Arrays;
public class AAA
{
public static void main(String[] args)
{
int[][] a = {{1,2,9,10,25},
{4,3,8,11,24},
{5,6,7,12,23},
{16,15,14,13,22},
{17,18,19,20,21}
};

//两种遍历方法
//第一种
/*for(int i=0;i<a.length;i++){
int[] b =a[i];
for (int j=0;j<b.length;j++ ){
System.out.print(b[j]+" ");
}
System.out.println();
}*/
//第二种
for(int i = 0;i <a.length;i++){
String s = Arrays.toString(a[i]);
System.out.println(s);
}

}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-09-18
一下应该就是你想要的,你只要改一下rowOfResults然后就可以形成不同大小的数组

public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("hello world");
int rowOfResults=5;
int result[][]=new int[rowOfResults][rowOfResults];
generate(rowOfResults-1,result);
for (int i=0;i<rowOfResults;i++){
for (int j=0;j<rowOfResults;j++){
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
public static void generate(int n, int result[][]){
if(n>-1){
if(n%2==0){
int value=n*n+1;
int row=n,col=0;
for (int i=0;i<(n+1)*(n+1)-n*n;i++){
if(col<n){result[row][col++]=value++;}
else if(col==n){result[row--][col]=value++;}
}
}
else {
int value=n*n+1;
int row=0,col=n;
for (int i=0;i<(n+1)*(n+1)-n*n;i++){
if(row<n){result[row++][col]=value++;}
else if(row==n){result[row][col--]=value++;}
}
}
generate(n-1,result);
}
}
}