How do I add commas when converting from Int [] to String?

Viewed 52

Hei I'm a beginner in Java and I have homework and I spent all day trying to figure out the solution and I couldn't. I'm so frustrated Can someone help me? Converting from any table in Int [] to string for eksmpel : int [] a = { 1,2,3} to String s = [1,2,3] I didn't know how to put the comma, it always shows a trailing comma at the end or at the beginning a trailing comma as well as parentheses.

This is my code :

    public class Test11 {

    public static String til(int[] tabell) {

        String str = "";
        String na1 = "[";
        String na2 = "]";
        String na3 = ",";
        String str3 = "";

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

            str += "," + tabell[i];

        }
        return str;
    }

    public static void main(String[] args) {
        int[] tab = { 1, 2, 3 };

        System.out.println(til(tab));
    }

}
2 Answers

You need to handle the first iteration through your loop as a special case, because you don't want to add a comma the first time around. There's something you can use to know that you're in the first iteration...the fact that the string you're building is empty because you haven't added anything to it yet.

This makes extra good sense because if the string is empty, then it doesn't yet contain a term that you want to separate from the next term with a comma.

Here's how you do this:

String str = "";
for (int i = 0; i < tabell.length; i++) {
    if (str.length() > 0)
        str += ",";
    str += tabell[i];
}

Use a variable to keep track of whether or not you're on the first iteration. If you are, don't put a comma before it.

boolean isFirst = true;
for (int i = 0; i < tabell.length; i++) {
  if (!isFirst) {
    str += ",";
  }
  isFirst = false;
  str += tabell[i];
}
Related