初始化数组String [] [] java

时间:2013-05-30 09:37:43

标签: java arrays null

我想创建一个String [] []数组并用String =“0”填充它的每个元素。我不明白为什么在这样做之后,当我尝试显示数组时,它给我的null值。这是代码。

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



            }
    }

2 个答案:

答案 0 :(得分:7)

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

您实际上并未将数组值设置为“0”,而只需重新分配局部变量k

您需要使用索引设置数组:

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

答案 1 :(得分:0)

更新:

此处k是对另一个对象的引用

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

替换为:

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

另见: Does Java pass by reference or pass by value?