【发布时间】:2017-03-31 19:08:01
【问题描述】:
我想知道是否可以就以下问题获得一些帮助。我需要创建一个以某种格式显示其输出的数组,但我似乎无法弄清楚如何真正让它这样做。这种模式有点难以用语言解释,所以我附上了一张可以展示它的图片。
下面提供的代码以下列方式显示输出:根据用户输入的数字,假设他们输入了 4,输出将是以下 4x4 数组:
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
这显然不是我想要实现的模式..所以任何帮助将不胜感激!
公开课第二题{
public static void main(String[] args) {
//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++)
{
if(i%2 == 0){
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
}
else{
for(int j=num-1;j>=0;j--)
{
array[i][j]=inc;
inc++;
}
}
}
//display formatted output
String [][]stringConvertedTable= new String[num][num];
for(int i=0; i<num; i++) {
for(int j=0; j<num; j++) {
stringConvertedTable[i][j]= Integer.toString(array[i][j]);
System.out.print(stringConvertedTable[i][j] + "\t");
}
System.out.println("");
【问题讨论】:
-
为什么需要这种模式?你想用它做什么?无论我怎么看,这样的模式都会变得凌乱而复杂。也许您可以采取另一种方法。
-
昨天不是问及回答了这个确切的问题吗? stackoverflow.com/questions/43129409/…
-
@downshift 网格匹配的图像。他们要么是合作伙伴,要么这是一项家庭作业。虽然我怀疑他能否找到这个问题,除非他很幸运。
-
哈哈,是的,这是一个家庭作业,我不倾向于为了好玩而做这些类型的模式xD