我是Java初学者,各位前辈帮个忙吧!
答题如下:int i=5;
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
int i=6
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
请问应该怎么打印出上面的数字,并且这样排列?
答题如下:int i=5;
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
int i=6
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
请问应该怎么打印出上面的数字,并且这样排列?
http://topic.csdn.net/u/20100308/15/38cee0b1-55ac-40c5-9550-9125dce9f513.html?98592
public class Test{
public static void main(String args[]) {
fun(8);
}
static void fun(int n){
int k=n-1;
int count=1;
int a[][]=new int[n][n];
for(int i=0;i<n/2;i++){
for(int j=i;j<k;j++){
a[i][j]=count++;
}
for(int j=i;j<k;j++){
a[j][k]=count++;
}
for(int j=k;j>i;j--){
a[k][j]=count++;
}
for(int j=k;j>i;j--){
a[j][i]=count++;
}
k--;
}
if(n % 2!=0){
int i=(n-1)/2;
a[i][i]=n*n;
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.printf("%4d",a[i][j]);
}
System.out.println();
}
}
}
for(int loop = 0;loop<10;loop++){
print(loop);
}
}
private static void print(int num){
int value = 1;
for(int i = 0;i<num;i++){
for(int j = 0;j<num;j++){
if(j==num-1){
System.out.println(value+" ");
}else{
System.out.print(value+" ");
}
value++;
}
}
}
}