【问题标题】:Java, 2D array specified organizationJava, 2D array specified organization
【发布时间】:2022-12-01 19:57:06
【问题描述】:

I have to make 2D array [10][10] to be filled like this: (https://i.stack.imgur.com/WCRGu.png) Please, can someone help me with this? `

    int j, i;
    int n=1;
    
    for (j=9; j>=0;j--) {
        for (i=11-j; i>=9-j; i++) {
            if(i<10) {
                a[i][j]=n;
                n++;
            }else{
                break;
            }
        }
    }

    for (i=0;i<=9;i++) {
        for(j=0;j<=9;j++) {
            System.out.print(a[i][j] + " ");
        }
        System.out.println();
    }

`

【问题讨论】:

  • What are the requirements here? Do you want to have a solution for exactly the numbers in the image or do you want a method that creates a 2D array based on some rules?
  • I want solution for exactly the numbers in the image.

标签: java arrays math multidimensional-array


【解决方案1】:

Here the program for your problem. I've also added the printing of the 2d array. It accepts any 1:1 size of the array, you can modify the size of your wanting using the final ARRAY_SIZE.

public class StackOverflow {

    public static void main(String[] args) {
        final int ARRAY_SIZE = 10;
        int[][] array = new int[ARRAY_SIZE][ARRAY_SIZE];

        //filling of values for 2d array
        for (int i = 0, k = 1; i < array.length ; i++) {
            for (int j = i + 3; j > i; j--, k++) {
                if (j > array.length) {
                    k--;
                    continue;
                }
                array[j - 1][array.length - i - 1] = k;
            }
        }

        //printing of 2d array
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                if (array[i][j] == 0) 
                    System.out.print(array[i][j] + "  ");
                else if (array[i][j] > 9) 
                    System.out.print(array[i][j] + " ");
                else
                    System.out.print(array[i][j] + "  ");
            }
            System.out.println();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 2021-07-06
    • 2019-03-12
    • 2016-08-04
    • 1970-01-01
    • 2011-08-12
    • 2021-05-05
    • 2021-11-01
    相关资源
    最近更新 更多