【发布时间】:2017-03-30 18:10:42
【问题描述】:
我已经弄清楚如何创建一个输出如下所示的数组:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
如果用户输入 4 表示 4x4 数组。 我的问题是我如何才能以某种方式操作此代码,使其按此顺序排列数组
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
每隔一行“向后”
`import java.util.Scanner; 导入 java.util.Arrays; 导入 java.util.Arrays;
公开课第二题{
public static void main(String[] args) {
//Title
System.out.println("[----------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[----------------------]");
System.out.println("");
//declare scanner
Scanner keyboard = new Scanner (System.in);
//Prompt user to enter a digit greater than or equal to 3
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");
//read user input
int num = keyboard.nextInt();
//place constraints on int num so that if it is less than 3, the program does not execute
while(num<3 )
{
System.out.println("Lets's try this again....");
System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
num = keyboard.nextInt();
}
//2D array with number of rows and columns entered by user
int[][] array = new int [num][num];
int inc=1;
for(int i=0;i<array.length;i++)
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
//replace all square brackets in array display & format into order
//replace all commas in array display
String a = Arrays.toString(array);
a = Arrays.deepToString(array).replace("], [", "\n").replaceAll("[\\[\\],]", "");
System.out.println(a);`
【问题讨论】:
-
不要使用
Arrays.deepToString。手动循环会更容易,也更明显。