代码之家  ›  专栏  ›  技术社区  ›  Rishav Sharma

数组在显示结果时是否跳过空位置?

  •  -2
  • Rishav Sharma  · 技术社区  · 6 年前

    我试着创造弗洛伊德的三角形,看起来像这样。

    1
    2 3
    4 5 6
    7 8 9 10
    

    但是在练习的时候我打错了,用这个代码创建了一个不同的三角形,

    class Main {
        public static void main(String[] args) {
            int value=1;
            int[][] arr = new int[4][4];
            for(int i=0;i<4;i++){
                for(int j=0;j<4;j++) {
    
                    if( i<=j ){
                        System.out.print(value+" ");
                        value++;
                    }
                }System.out.println();
            }
    
        }
    }
    

    1 2 3 4                                                                                                                                        
    5 6 7                                                                                                                                          
    8 9                                                                                                                                            
    10
    

    现在我的问题是,在阅读有关数组的内容时,我看到特定位置的特定值会被打印出来。

    如果这是真的,那么这个代码的输出应该是这样的,

    [1][2][3][4]
    [x][5][6][7]
    [x][x][8][9]
    [x][x][x][10]
    

    数组在显示结果时是否跳过这些空字段? 请帮助理解这一点

    4 回复  |  直到 6 年前
        1
  •  0
  •   that other guy    6 年前

    不,数组不会跳过这些值。

    跳过它们是因为您编写了代码,以这种条件的形式跳过它们:

          if( i<=j ){
              System.out.print(value+" ");
              value++;
          }
    

    如果删除该条件,将打印所有16个值。

        2
  •  0
  •   Piohen    6 年前

                if( j <= i ){
                    System.out.print(value+" ");
                    value++;
                }
    

    我想如果你停止使用人工神经会容易些 j .

    但是,请注意,在Java中,您创建的不是二维数组,而是一个数组数组,数组的大小可以是任意维。

        3
  •  0
  •   Max S    6 年前

    它会将0打印为0,因为当数组初始化时,所有值都设置为0,如果您打印它们,它们会这样打印。这里有一个链接

    What is the default initialization of an array in Java?

        4
  •  0
  •   ankit rai    6 年前

    不,正如另一个人所说,是if条件在跳过。 试试这个程序-

    public class MyClass {
    
        public static void main(String args[]) {
            int value=1;
            int[][] arr = new int[4][4];
            for(int i=0;i<4;i++){
                for(int j=0;j<4;j++) {
    
                    if( i<=j ){
                        System.out.print(value+" ");
                        System.out.print("\t");
                        value++;
                    } else {
                        System.out.print(0);
                        System.out.print("\t");
                    }
                }System.out.println();
            }
    
        }
    }
    

    这是印刷的-

    1 2 3 4
    0 5 6 7

    注意-程序中不使用arr。