简体   繁体   English

初始化数组String [] [] java

[英]initializing array String[][] java

I would like to create a String[][] array and fill every element of it with String = " 0". 我想创建一个String [] []数组,并用String =“ 0”填充它的每个元素。 I do not understand why after doing this, when I try to display the array its giving me null's values. 我不明白为什么这样做之后,当我尝试显示数组时会给我null值。 Here is code. 这是代码。

    import java.util.Vector;

    public class hetmani{

private int n;
private String[][] tab;
private Vector wiersz;
private Vector kolumna;


public hetmani(int liczba){

    n=liczba;
    wiersz = new Vector();
    kolumna = new Vector();
    tab = new String[n][n];

}

public void wyzeruj(){

    for (String[] w : tab){
        for (String k : w){
            k = " 0";
            System.out.print(k);
            }
        System.out.println();
    }

}
public void wyswietl(){

    for (String[] i : tab){
        for (String j : i){
            System.out.print(j);}
                System.out.println();}
}


public static void main(String[] args){

    hetmani szach = new hetmani(3);

    szach.wyzeruj();
    szach.wyswietl();



            }
    }
for (String k : w){
            k = " 0";

You aren't actually setting the array values to " 0", you are just reassigning the local variable k . 您实际上并没有将数组值设置为“ 0”,而只是在重新分配了局部变量k

You would need to set the array using indexes: 您将需要使用索引设置数组:

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

update: 更新:

here k is reference to another object 这里k是另一个对象的引用

for (String k : w){
        k = " 0";
        System.out.print(k);
}

replace to: 替换为:

    for(int i=0;i<w.length;i++){
            w[i] = "0";
        }

also see: Does Java pass by reference or pass by value? 另请参见: Java是按引用传递还是按值传递?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM