1

I need to print the array in this order example: [1, 2, 3, 4], but I don't know how to do it. I started like this:

 for (int i = 0; i < a.length - 1; i++) {
        return "[" + a[i] + ", "+ "]";
    }
return null;

But I only got the first element printed like [1, ]. Can you help me?

1
  • You shouldn't be returning from inside the loop: you need to build up the toString, and then return it after the loop. Commented Oct 9, 2015 at 22:51

6 Answers 6

3

Call Arrays.toString(a):

int[] a = {1,2,3,4};
System.out.println(Arrays.toString(a));

Output

[1, 2, 3, 4]
Sign up to request clarification or add additional context in comments.

1 Comment

Better to correct the current OP code before giving him the built in method :)
2

Don't return with single iteration. You have to build the string for all the iterations and then return from there .

        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (int i = 0; i < a.length - 1; i++) {
            builder.append(a[i]).append(",");
        }
        builder.append("]");
        if (builder.length() > 1)
        builder.setLength(builder.length() - 1);
        return result;

Seems you are learning about arrays and playing with loops.

If you want to use any built in method to do the job use Arrays.toString(a);

4 Comments

That's excessive. Truncate the builder instead: if (builder.length() != 0) builder.setLength(builder.length() - 1) before append("]").
@Andreas Hmm fails in case of empty array. But Idea is good to avoid regex :)
Fails how? The if statement prevents that.
I said before append("]"), otherwise you're removing the ]. ;-)
1

The problem with your code is that you are returning at the first loop iteration.

There are other better and cleaner ways to do it like using:

Arrays.toString(array)

So, you can have:

@Override 
String toString() {
    return Arrays.toString(a);
}

Comments

1

This statement also produces the desired output

System.out.print(Arrays.asList(a));

Comments

0

Build the string in the loop, but don't return until you have processed all the elements:

@Override String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append("[");
  for (int i = 0; i < a.length - 1; ++i) {
    sb.append(a[i]);
    sb.append(", ");
  }
  if (a.length > 0) {
    sb.append(a[a.length - 1]);
  }
  sb.append("]");
  return sb.toString();
}

I'm assuming that you want to append all elements in the array, you are not intentionally excluding the last one.

Using a StringBuilder is preferable to plain string concatenation, since it is more efficient to accumulate lots of strings that way.

Comments

0
public static void main(String[] args)
  {
    int[] a = {1,2,3,4};
    String res=null;
    int num;
    res = "[";


    for (int i = 0;  i < a.length;  i++) {

      num = a[i];
      res = res + num +",";

    }
    res = res + "]";
System.out.println (res);
}

We build the string during the loop appending to the previous string the next number until the end. Then we print the full string! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.