Java循环数组模式

时间:2017-03-31 19:08:01

标签: java arrays

我想知道我是否可以从以下问题中得到一些帮助。我需要创建一个以某种格式显示其输出的数组,但我似乎无法弄清楚如何真正实现它。这个模式有点难以用文字解释,所以我附上了一个展示它的图像。

Pattern example

下面提供的代码以下列方式显示输出:根据用户输入的数字,假设他们输入4,输出将是以下4x4数组:

1 2 3 4

8 7 6 5

9 10 11 12

16 15 14 13

这显然不是我想要实现的模式..所以任何帮助都会受到赞赏!

公共课题2 {

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("");

1 个答案:

答案 0 :(得分:0)

您可以通过应用具有数组大小的模运算符来实现计数器的包装

result[i][(k+i)%size] = counter++;

怎么样?

    final int size = 5;
    int[][] result = new int[size][size];

    //the logic
    int counter = 1;
    for(int i = 0; i < size; i++) {
        for(int k = 0; k < size; k++) {
            result[i][(k+i)%size] = counter++;
        }
    }

    //just the output
    for(int i = 0; i < size; i++) {
        boolean isFirst = true;
        for(int k = 0; k < size; k++) {
            if(isFirst)
                isFirst = false;
            else
                System.out.print(", ");
            System.out.print(result[i][k]);
        }
        System.out.println();
    }

输出

1, 2, 3, 4, 5
10, 6, 7, 8, 9
14, 15, 11, 12, 13
18, 19, 20, 16, 17
22, 23, 24, 25, 21