grafter
grafter

Reputation: 11

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



            }
    }

Upvotes: 1

Views: 153

Answers (2)

liuzhijun
liuzhijun

Reputation: 4469

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?

Upvotes: 0

Supericy
Supericy

Reputation: 5896

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

Upvotes: 7

Related Questions