Reputation: 161
I wrote a toString method to consists of a list of this buffer's Strings in order from front to rear, enclosed in square brackets ("[]"). Adjacent Strings are separated by the characters ", " (comma and space). The letter "R" should appear to the left to indicate the rear of the buffer and the letter "F" should appear to the right to indicate the front of the buffer. Fore example, a buffer containing the strings "A", "B", and "C" would be represented as "R[A, B, C]F".
and then return a string representation of the buffer.
public String toString(){
String s = "[";
for(int h = 0, h <array.length, h++){
s += array[h];
s+= ",";
}
s+="]";
return s;
}
I'm receiving an error on my for loop saying that ";" is expected and that incompatible types int can't be converted into boolean
Upvotes: 0
Views: 50
Reputation: 285405
for loops need ;
not ,
separators.
Change
for(int h = 0, h <array.length, h++){
to
for(int h = 0; h < array.length; h++) {
So to put together...
@Override
public String toString() {
String s = "[";
for (int h = 0; h < array.length; h++) {
s += array[h];
if (h != array.length - 1) {
s += ", ";
}
}
s += "]";
return s;
}
Note, if array is quite large, or if this toString will be called a lot, it is more efficient to use a StringBuilder than to use a String since fewer objects are created:
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int h = 0; h < array.length; h++) {
sb.append(array[h]);
if (h != array.length - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
If this is not the case, then this may be premature optimization.
Upvotes: 6