Search code examples
javaarraysmethodstostring

How do you print out a string that has each element of an array four to a line


This is my code

public String toString() {
    String B = A[0] + " ";
    for (int w = 1; w < this.A.length; w-=-1) {
        B += A[w] + " ";
        if(w % 4 == 0)
            B += "\n";
    }
    return B;
}

I am trying to make a string that has each element of my array in it and after every fourth element a new line is added. The output should be something like this:

AA BB CC DD
EE FF GG HH
II JJ KK LL
MM NN OO PP

I am writing a toString method for a java class. The array has 52 elements Instead I keep getting this as an output:

1S 4S 6S 2S 8S 
8S 7S 3S 7S 
6S 8S 5S 6S
3C 3C 1C 8C 
8C 9C 4C 

Solution

  • Using StringBuilder:

    private static void printArray(String[] array) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < array.length; i++) {
            if(i > 0 && i % 4 == 0) {
                sb.append("\n");
            }
            sb.append(array[i]);
            sb.append(" ");
        }
        System.out.println(sb);
    }