Home > Software design >  Bring 2d array contents into 1d array Java
Bring 2d array contents into 1d array Java

Time:05-01

I am trying to recreate the Thue Morse sequence in Java console and need to bring the contents of a 1 dimensional array into a 2 dimensional one. I tried using 2 for loops, with one nested, but receive the Ljava.lang.String;@42d3bd8b as a result

    int x = Integer.parseInt(args[0]);
    String[][] array = new String [x][x];
    String thue   = "0";
    String morse  = "1";


    //
    for (int i = 1; i <= array.length; i  ) {
        String t = thue;             // save away values
        String m = morse;
        thue   = m;
        morse  = t;

    }

    String[] split = (thue.split("(?!^)"));

    for (var y = 0; y<split.length; y  ){
        if (split[y] == "0"){
            split[y] = " ";
        }
        else split[y] = "-";
    }
    int index = 0;
    for (var i = 0; i < array.length; i  ){
        for (var j = 0; j < array[i].length;j  ){
            array[i][j] = (split[index]);
            index  ;
        }
    }
    System.out.println(Arrays.toString(array));

    }



}

CodePudding user response:

There are 2 corrections to be made

1)in this code

   if (split[y] == "0"){
        split[y] = " ";
    }

Strings cannot be compared as primitives. Replace equals operator with equals method as such

    if (split[y].equals("0")){
        split[y] = " ";
    }

2)Arrays toString method can be used to convert only 1D arrays to string format.

You have to use the deepToString for your purpose

System.out.println(Arrays.deepToString(array));

CodePudding user response:

I found out how to fix it, I converted array into a integer array and then later on when setting split[index] equal to the indicies of array, I just added and Intger.parseInt around the split[index]

  • Related