Home > other >  Having problems converting a char 2d array to a 2d char array list
Having problems converting a char 2d array to a 2d char array list

Time:12-15

Alright, I've been working on the code to take a double char array and turn it into a double array list, So far I've been using two for loops to achieve this, adding the characters of each array in the double array to an array list then adding that back into the double array list. Below is the code for my converter:

public static ArrayList<ArrayList<Character>> CharAToAL(char[][] chars){
        ArrayList<ArrayList<Character>> c = new ArrayList<>();
        ArrayList<Character> b = new ArrayList<>();

        for(int i=0; i < chars.length; i  ){
            b.clear();
            for (int k=0; k < chars[i].length; k  ){
                b.add(Character.valueOf(chars[i][k]));
//this part of code prints out the correct letters
                Debug.printLn(String.valueOf(chars[i][k]));
            }
            c.add(b);
        }
        return c;
    } 

And I'm testing it using this code:

//static obj outside of main
    static char[][] gamemenu = {
            {'0','1','0','0','0','0','0','0','0','0'},
            {'0','0','0','0','0','0','0','0','0','0'},
            {'0','0','0','0','@','0','0','0','0','0'},
            {'0','0','0','0','0','0','0','0','0','0'},
            {'0','0','0','0','0','0','0','0','0','0'}
    };
//inside of main
    ArrayList<ArrayList<Character>> e = Utility.CharAToAL(gamemenu);
    Debug.PrintDoubleArray(gamemenu);
    Debug.printLn("\n-------");
    Debug.PrintDoubleArray(e);
    Debug.printLn("\n-------");
    Debug.printLn(String.valueOf(e.get(0).get(1)));

Debug is just a small script that helps with printing out values. What I expect to see is the gamemenu, however, it is printing only zeros as shown in the picture below, Above dash is expected and below is what gets put out.

Picture of the printout

I think it could be caused by clearing b but not doing that causes the same thing to repeat over and over. Thank you in advance! :>

CodePudding user response:

b does not need to be declared outside the loop

for(int i=0; i < chars.length; i  ){
    ArrayList<Character> b = new ArrayList<>();
    for (int k=0; k < chars[i].length; k  ){
        Character ch = Character.valueOf(chars[i][k]);
        b.add(ch);
        //this part of code prints out the correct letters
        System.out.println(ch);
     }
    c.add(b);
}

when you do clear it is removing all from the list, and as you are not creating a new List, the previously added values are also lost.

  • Related