The example in this article describes the operation of rotating a two-dimensional array in Java and is shared with everyone for your reference. The specific implementation method is as follows:
Copy the code code as follows:
package test;
/*
* 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
*
* Write a method to print a two-dimensional array of equal length, requiring the natural numbers starting from 1 to be arranged in a spiral manner from the outermost circle of the square matrix inwards.
* */
public class Test6
{
public static void main(String[] args)
{
arraynum(4);
}
// It’s easy to change the code. Input different y values and output different two-dimensional arrays.
private static void arraynum(int x)
{
int[][] arr = new int[x][x];
int len = arr.length, max = 0, count = 0;
specArr(arr, len, max, count);
arrprint(arr);
}
// Used for advanced for output printing
private static void arrprint(int[][] arr)
{
for (int[] in : arr)
{
for (int t : in)
{
System.out.print(t + "/t");
}
System.out.println();
}
}
private static void specArr(int[][] arr, int len, int max, int count)
{
while (len > 0)
{
int j = 0;
for (int index = 0; index < (len - 1) * 4; index++)
{
if (index < len - 1)
arr[0 + count][index + count] = ++max;
else if (index < 2 * (len - 1))
arr[count + j++][arr.length - 1 - count] = ++max;
else if (index < 3 * (len - 1))
arr[arr.length - 1 - count][(j--) + count] = ++max;
else if (index < 4 * (len - 1))
arr[arr.length - 1 - (j++) - count][0 + count] = ++max;
}
if (len == 1)
{
arr[arr.length / 2][arr.length / 2] = max + 1;
}// Note that when the y value is an odd number, there will be a loop to n=1, and the middle value of the array needs to be supplemented.
count++;
len = len - 2;
}
}
}
I hope this article will be helpful to everyone’s Java programming.