Home > Software engineering >  How to make a clean toString for multiple 2 dimensional array
How to make a clean toString for multiple 2 dimensional array

Time:03-15

I have an ArrayList which contains some object which has an attribute called grid which is 2 dimensional array filled with numbers.

I want to print the grids next to each other like a "big grid of grid", separated by a character, not line by line and there should be maximum 6 arrays next to each others. I've tried to print the rows of the first 6 arrays one by one then I go to the next line but i'm getting lost and it's not working properly.

I'm trying to have this

enter image description here

but like this

enter image description here

So far, this is what i've done:

public String toString() {
    String s = "";
    int count = 0;

    for (int i = 0; i < square.size(); i  ) {

        for (int k = 0; k < 5; k  ) {
            
            for (int j = 0; j < 5; j  ) {
                

                if(square.get(i).getGrid()[k][j] >= 10){
                    if(j == 0){
                        s ="| " String.valueOf(square.get(i).getGrid()[k][j]) " ";
                    }
                    if(j == 4){
                        s =String.valueOf(square.get(i).getGrid()[k][j]) " |";
                    }
                    if(j!= 0 && j !=4){
                        s =String.valueOf(square.get(i).getGrid()[k][j]) " ";
                    }
                }

                else{
                    if(j == 0){
                        s ="| " String.valueOf(square.get(i).getGrid()[k][j]) "  ";
                    }
                    if(j == 4){
                        s =String.valueOf(square.get(i).getGrid()[k][j]) "  |";
                    }
                    if(j!= 0 && j !=4){
                        s =String.valueOf(square.get(i).getGrid()[k][j]) "  ";
                    }
                }

            }
            count  ;

            if(count == 6){
                count = 0;
                s  = "\n";
            }
        }


    }

    return s;

The counter is for the number of array I want next to each others.

Is there a better way to do it?

CodePudding user response:

It looks like you are most of the way there, we just need to construct each individual line as we go which we can do by modifying your existing code a little to use a list of strings that we can append as we go rather than a single string that is going to be a pain to format. We can combine and return the single string at the end instead:

//Create a list of lines to print so that we can append to the end of each line as we go
ArrayList<String> linesToPrint = new ArrayList<>();

//Populate the list with blank strings
for (int i = 0; i < square.size(); i  )
{
    linesToPrint.add("");
}

//Loop through the list of squares
for (int i = 0; i < square.size(); i  )
{
    //Put the count inside the loop so it resets every time
    int count = 0;
    //loop throughthe rows
    for (int k = 0; k < 5; k  )
    {
    //Create a blank string to store the current grid row
    String row = "";
    //loop through the columns
    for (int j = 0; j < 5; j  )
    {
        //Format double didgits
        if (square.get(i).getGrid()[k][j] >= 10)
        {
        if (j == 0)
        {
            row  = "| "   String.valueOf(square.get(i).getGrid()[k][j])   " ";
        }
        if (j == 4)
        {
            row  = String.valueOf(square.get(i).getGrid()[k][j])   " |";
        }
        if (j != 0 && j != 4)
        {
            row  = String.valueOf(square.get(i).getGrid()[k][j])   " ";
        }
        }
        //Format single didgets
        else
        {
        if (j == 0)
        {
            row  = "| "   String.valueOf(square.get(i).getGrid()[k][j])   "  ";
        }
        if (j == 4)
        {
            row  = String.valueOf(square.get(i).getGrid()[k][j])   "  |";
        }
        if (j != 0 && j != 4)
        {
            row  = String.valueOf(square.get(i).getGrid()[k][j])   "  ";
        }
        }
    }
    
    //Once the row has been created store it in the list
    linesToPrint.set(count, (linesToPrint.get(count))   row);
    count  ;
    }
}

//Construct the complete string
String s = "";
for (int i = 0; i < square.size(); i  )
{
    s  = linesToPrint.get(i)  "\r\n";
}
return s;

Now the returned string should work as desired.

Note that this will only display correctly when using a console with a monospaced font.

CodePudding user response:

Need to construct display line by line as iterate through lists. Eg: Line1 = List1Line1 List2Line1 etc Used an auxiliary list:result to keep Lines (mainly each ordered elements).

Test Lists are populated with dummy values so each list contains elements from 1-25 in random order. Simple output check is to inspect elements from individual lists to see if all fulfill a group 1-25.

public class TestArrayPrint {

    static List<Integer>[] list =  new ArrayList[5];
    static List<String> result = new ArrayList<String>();
    public static void main(String[] args) 
    {
        //dummy values 
        for(int i=0;i<list.length;i  )
        {
            list[i] = IntStream.rangeClosed(1, 25).boxed().collect(Collectors.toList());
            Collections.shuffle(list[i]);
        }
    
        //full scan
        for(int k=0;k<list.length;k  )
        {
            //next line
            for(int i=0;i<list.length;i  )
            {
                //add first line from first list, then first line from second list, etc
                for(int j=0;j<list.length;j  )
                {
                    //covert to 2 string digits for display 
                    String s= (list[i].get(0)<10) ? " " list[i].get(0) : list[i].get(0).toString() ;
                    list[i].remove(0);
                    //elements will be in order 
                    //Line1List1 Line1List2 ...
                    //Line2List1 Line2List2 ...
                    result.add(s);
                }
            }
        }
        //result.forEach(System.out::println);
        System.out.println("Ordered Elements to Display=" result.size() "\n");
        
        //display
        //just adapt i,j,k for various matrix sizes
        for(int i=0;i<5;i  )
        {
            StringBuffer line = new StringBuffer();
            for(int j=0;j<5;j  )
            {
                for(int k=0;k<5;k  )
                {
                    if(k==0)
                    {
                        line.append("| " result.get(0));
                        result.remove(0);
                    }
                    else if(k==4)
                    {
                        line.append(" " result.get(0) " |");
                        result.remove(0);
                    }
                    
                    else
                    {
                        line.append(" " result.get(0));
                        result.remove(0);
                    }
                }
            }
            System.out.println(line);
        }   
    }
}

Output

Ordered Elements to Display=125

| 11 12  5 13 15 ||  1 24 19 22 13 ||  6  9  8  3 13 || 18  3 10 14  2 || 19 21  3 23 18 |
| 20 24 21  3  7 || 12 14  7  8 16 || 11  4 23  1  5 ||  6  8 13 23 15 || 20 12  7 13  6 |
|  8 18  1 25  2 ||  9  3  2 25 17 || 12 17 21 20 16 || 12 24 17 20 22 || 10  1 16 15  8 |
| 23 22  4 17 16 || 10 21 18  4 11 || 25 24 14 22  2 ||  7  4  5  9 19 ||  9  5 14 11  2 |
|  9 10 19 14  6 || 23 15  5 20  6 || 18 10  7 19 15 || 11 16 21  1 25 || 24 17 25 22  4 |

Note: Is irrelevant if your list have methods to get a specific element, the mechanism should be something similar (remove processed element could be useful even for your logic). On my example elements flows in lines so element(6) : list.get(5) is grid(1,0).

  • Related