1

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



            }
    }
1
  • Format your code as this will increase your chances of getting an answer to your question. Commented May 30, 2013 at 10:05

2 Answers 2

7
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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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?

2 Comments

String being immutable is actually irrelevant to the question/problem at hand.
oh,yes ,sorry!this problem is nothing with immutable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.