package fish3dry2;
import java.util.Scanner;
public class ClockWisePrint {
static int arr[][];//二维数组用来存储数字
static int currentNumber = 1;// 从1开始打印,用来控制整个流程需要打印的数字
static int num = 0;//用来判断何时可以打印
public static void moveRight(int count, int rowIndex, int columnIndex) {//count表示移动几步,由题目可以看出右移时候次数和是用户输入的数字,下移减1,左移不变,上移减1,右移不变
if(judge()){//如果数组已经赋值结束,就打印出来
print();
}else{
int temp = 0;//临时变量
while (temp < count) {
arr[rowIndex][columnIndex] = currentNumber;
temp ++;//临时变量自增
columnIndex++;//向右移动
currentNumber++;//当前要打印的数字自增
}
//count--;//将打印次数减1
columnIndex--;//下标归位
rowIndex--;//下移一位
moveUp(count,rowIndex,columnIndex);
}
}
public static void moveDown(int count,int rowIndex,int columnIndex) {
if(judge()){
print();
}
else{
int temp = 0;
while(temp < count){
arr[rowIndex][columnIndex] = currentNumber;
temp ++;
rowIndex++;
currentNumber++;
}
count--;
rowIndex--;
columnIndex++;//左移一位
moveRight(count, rowIndex, columnIndex);
}
}
public static void moveLeft(int count,int rowIndex,int columnIndex) {
if(judge()){
print();
}
else{
int temp = 0;//临时变量
while(temp < count){
arr[rowIndex][columnIndex]=currentNumber;
temp ++;
columnIndex--;//左移一位
currentNumber++;//数字自增
}
//count--;//次数减1
columnIndex++;
rowIndex++;//上移一位
moveDown(count, rowIndex, columnIndex);
}
}
public static void moveUp(int count,int rowIndex,int columnIndex) {
if(judge()){
print();
}
else{
int temp = 0;
while(temp < count){
arr[rowIndex][columnIndex] = currentNumber;
temp ++;
rowIndex--;
currentNumber++;
}
count--;
rowIndex++;
columnIndex--;//右移一位
moveLeft(count, rowIndex, columnIndex);
}
}
public static void print(){//在控制台打印
for(int row[]:arr){
for(int column:row){
System.out.print(column+"\t");
}
System.out.println();//换行打印
}
}
public static boolean judge(){
if(currentNumber>Math.pow(num, 2)){//如果数组已经赋值结束,就打印出来
return true;
}else{
return false;
}
}
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);//获取输入流
System.out.println("请输入您希望打印的矩阵的最大的值:");//打印提示信息
String input = in.next();//获取用户的输入
int count = 0;//计数器
if (input.matches("\\d+")) {// 输入正确,用来检验用户输入的是否是数字
num = Integer.parseInt(input);
count = num;// count用来控制在每一个方向上打印几个数字,第一次打印时候和用户输入的数字相同
}
else {
System.out.println("您输入的数据不正确,系统推出!");
System.exit(0);
}
arr = new int[num][num];//实例化数组
moveDown(count, 0, 0);//调用左移函数
}
}
创建一个二维数组,按照顺时针方向为二维数组赋值,有先向下,再向右,再向上,再向左循环赋值,检测是否为二维数组赋值完毕,如果复制完毕,输出二维数组。