1. 程式人生 > >Java從控制檯輸入一個數n,就列印n*n的正方形.Z字形。

Java從控制檯輸入一個數n,就列印n*n的正方形.Z字形。

從控制檯輸入一個數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);
}


}