2

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 
LoopGod
  • 67
  • 5
  • 1
    `w-=-1` I mean yes, but that is an odd way to add one to `w`. What output do you get, what output do you expect? – Elliott Frisch Feb 17 '20 at 16:53
  • 1
    Why this weird loop? Why doesn't `w` start from 0 and why do you use `w -= -1` instead of using `w++`? – RealSkeptic Feb 17 '20 at 16:53
  • What problem(s) do you have with this code? – Scott Hunter Feb 17 '20 at 16:53
  • 3
    No, don't add information in the comments. Instead, [edit] the question, add the information there - properly formatted - and use the comments only to let us know that you have added information to the question. Comments are not meant for code or formatted output. – RealSkeptic Feb 17 '20 at 16:56

2 Answers2

2

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);
}
falknis
  • 141
  • 7
1

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++.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43