Java 2D数组:如何按顺序填充元素

时间:2015-05-13 17:28:34

标签: java arrays

给定数组int[][] arr = new int[a][a];

我想使用以下规则来填充矩阵的一半

公式可以简化为

a[i][j]=input(其中i = j)

a[i][j]=a[i-1][j+1](其中i!= j)

因此只需要一半的矩阵。

目前我已完成第一个循环,但不知道如何使其迭代继续

这就是我所做的:

for (int i=0;i<a.length;i++){
    for(int j=0;j < a[i].length;j++){
        if(i==j){
            a[i][j]=keyboard.nextInt();;
        }
    }             
}

现在这只能填充第一组

enter image description here

我一直在继续循环计算元素来实现这个

enter image description here

然后

enter image description here

最后,

enter image description here

我认为关键部分是设定指数。

3 个答案:

答案 0 :(得分:0)

如果要填写上半部分的值为x

for (i = 0; i < a; ++i)
    for(j = 0; j < a; ++j)
        if(i <= j)
            arr[i][j] = x;

答案 1 :(得分:0)

您可以使用以下代码填充该序列中的2D数组:

var arr = [];

// Add 3 zero-filled arrays with different lengths
arr.push(new Array(4+1).join('0').split('').map(parseFloat));
arr.push(new Array(8+1).join('0').split('').map(parseFloat));
arr.push(new Array(6+1).join('0').split('').map(parseFloat));

k = 1;
stillFilling = true; j = 0;
while(stillFilling){

    stillFilling = false;   
    for(i=0;i<arr.length;i++){
        if ((i+j)<arr[i].length){
            arr[i][(i+j)]=k; // here you assign the value.
            stillFilling = true;
            k++;
        } 
    }
    j++; 
}

ember-parse-adapter

的JSFiddle中查看行动

答案 2 :(得分:0)

char[][] m = new char[7][7];
    for(int i=0; i<m.length; i++) {
        for(int j=i; j<m.length; j++) {
            m[i][j] = '*';
        }
    }

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