Java从控制台输入一个数n,就打印n*n的正方形.Z字形。

版权声明: https://blog.csdn.net/qq_41342776/article/details/80410810

从控制台输入一个数n,就打印n*n的正方形,其规律如下:


第一种方法;

package org.ganhua.love;



import java.util.Scanner;


public class Main2 {
static Scanner sc = new Scanner(System.in);


public static void main(String[] args) {
boolean isRight = true;// 填数方向默认为右上 true=右
System.out.println("请输入一个整数");
n = sc.nextInt();// 输出几行
int[][] num = new int [n][n];
next(isRight, num, 0, 0, 1);
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
System.out.print(num[j][i] + "\t");
}
System.out.println();
}
}


private static int n;// 输入的n值


/**
* 填入下一个数
*
* @param isRight
*            下个数的填数方向 true右上 false 左下
* @param num
*            需填充的数组
* @param x
*            填的下一个数的一维坐标
* @param y
*            填的下一个数的二维坐标
* @param nextNum
*            下一个填的数字
*/
public static void next(boolean isRight, int[][] num, int x, int y, int nextNum) {


if (nextNum > n * n) {
return;
}
num[x][y] = nextNum;


if (isRight) {// 方向为右上


if (y == 0 || x == n - 1) {// x或y达到边界
isRight = false;// 改变方向为左下
}


if (x == n - 1) {// x到达边界 y
y++;
} else if (y == 0) {// x在边界内 y到达边界
x++;
} else {// 都在边界内
x++;
y--;
}
} else {// 方向为左下


if (x == 0 || y == n - 1) {// x或y达到边界
isRight = true;// 改变方向为右上
}
if (y == n - 1) {// y到达边界
x++;
} else if (x == 0) {// x在边界内 y到达边界
y++;
} else {// 都在边界内
y++;
x--;
}
}
nextNum++;
next(isRight, num, x, y, nextNum);
}

}

第二种方法:

package org.ganhua.love;


import java.util.Scanner;


public class Main3 {
static Scanner sc = new Scanner(System.in);


public static void main(String[] args) {
System.out.println("请输入一个整数");
int num = sc.nextInt();
name(num);
}


static void printArray(int[][] a) {
int rows = a.length;
int cols = a[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println("");
}


System.out.println("============================");
}


public static void name(int N) {
int[][] a = new int[N][N];
int count = 1;
for (int n = 0; n < 2 * N - 1; n++) {
int i = 0;
if (n < N) {
for (i = 0; i <= n; i++) {
if (n % 2 == 0) {
a[n - i][i] = count;
} else {
a[i][n - i] = count;
}
count++;
}
} else {
int counts = 2 * N - n - 1;
int c1 = 0;
for (i = n - N + 1; c1 < counts; i++, c1++) {
if (n % 2 == 0) {
a[n - i][i] = count;
} else {
a[i][n - i] = count;
}
count++;
}
}
}
printArray(a);
}


}

猜你喜欢

转载自blog.csdn.net/qq_41342776/article/details/80410810