简体   繁体   中英

initializing array String[][] java

I would like to create a String[][] array and fill every element of it with String = " 0". I do not understand why after doing this, when I try to display the array its giving me null's values. 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 .

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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