Chechin
Chechin

Reputation: 1

Bidimensional array to single array

Hi people of the community, i have this problem, i'm trying to pass a bidimensional array to a simple array(more explicit: String[][] to String[]), and always is the same. it marks me null in the first position of the array when i convert the String[][] to String[] i've try everything i know but nothing works to erase the null space into the array. someone can help me? here is the code:

public class main {

    public main(){

        String[][] str={
                {"uno","dos","tres"},
                {"unos","dose","trese"},
                {"uno","dos","tres"},

        };

        String[] str2=new String[3] ;

        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                str2[i]+=str[i][j];

            }
        }


        for(int i=0;i<3;i++){

                System.out.print(str2[i]);
                System.out.print("\n");
            }

    }

    public static void main(String[] args) {
        new main();

    }

and this is the result i got:

nullunodostres

nullunosdosetrese

nullunodostres

now you can see, it turns the String[][] into String[], but always keep the null at first position. and if i try to start the loop i=1 instead of i=0, just disappear the first position of the values but the null continues.
Please help me.

Upvotes: 0

Views: 72

Answers (2)

Amby
Amby

Reputation: 462

Its because initially every element in a array of string is implicitly initialized to null

You have to explicitly assign it in order to get rid of null

for example str2[0]="";

Upvotes: 0

That's because you're not initializing the values inside str2 to anything, and so they all have the value null. When you use string contatenation (+), the value null gets converted to the string "null" and put in front of your first element's value. Try this:

String[] str2 = new String[3];
Arrays.fill(str2, "");

Upvotes: 2

Related Questions