Home » Java » java – How do you print out a string that has each element of an array four to a line-Exceptionshub

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

Posted by: admin February 25, 2020 Leave a comment

Questions:

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 
How to&Answers:

All you have to do is:

String B = A[0] + " ";
for (int w = 1; w < this.A.length; w-=-1) {
    if (w % 4 == 0) {
        B += "\n";
    }
    // this line is after the check because you already added the first
    // element to the string before the loop
    B += A[w] + " ";
}

Also: Appending to a String in a loop is an expensive operation because Strings in java are immutable. Use StringBuilder instead. Read more here.

I do not understand w-=-1 over w++.

Answer:

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);
}