/**
* 6-3
* Programming to achieve the following requirements of the spiral matrix
* The spiral phalanx is stored in a two-dimensional array of n*n and prints the output
* Requires N to be read in by the program
* Digital Spiral Phalanx is automatically generated by the program
* (non-human initialization or input individually)
*/
import java.io.*;import java.util.*;p ublic class test{public static void Main (String[] args) {/* declares that a dimension is an array of n */int n=0; System.out.print ("Please enter the dimension n of the Spiral Matrix:"); Scanner read = new scanner (system.in); N = read.nextint (); int array[][] = new int[n][n];/* assigns values to individual elements in an array */int elem = 1; //initializes the value of the first element to 1int cyclenumber=0;//count the number of cycles if (n % 2 != 0) cyclenumber=n/2+1;elsecyclenumber=n/2;for (int i = 0; i < cyclenumber; i++) {//start loop for from outside to inside (int j = i; j < n-i; j++)//left-to-right assignment {array[i][j]=elem;elem++;} for (int k = i+1; k < n-i; k++)//assignment from top to bottom {array[k][n-i-1]=elem;elem++ ;} for (int l = n-i-2; l >= i; l--)//right-to-left assignment {array[n-i-1][l]=elem;elem+ +;} for (int m = n-i-2; m > i; m--)//from bottom to topassignment {array[m][i]=elem;elem++;}} /* Output array */for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) System.out.printf ("%-3d", array[i][j]); System.out.println ();}} }
This article is from the "hacker" blog, make sure to keep this source http://anglecode.blog.51cto.com/5628271/1619860
Those years, learn together Java 6-3