-1

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

}
Temo
  • 7
  • 1
  • 1
    YIp, this is a very common programming problem. So reason it through. What's the problem really? Isn't it that the first time through the loop, you don't want to add a comma before adding the next integer? So how could you enhance your code just a bit to deal with the special case.? (Hint: the string `str` is empty at that point). \ – CryptoFool Sep 23 '22 at 23:41
  • 1
    `public static String til(int[] table) { return Arrays.toString(table); }` (note: This will have a space after each comma.) – Old Dog Programmer Sep 24 '22 at 02:12
  • 1
    Use `StringBuilder` rather than `String` concatenation ... if you expect the array may be large. You can also solve this using `StringJoiner` or Java 8 streams. – Stephen C Sep 24 '22 at 03:19

2 Answers2

4

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];
}
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
CryptoFool
  • 21,719
  • 5
  • 26
  • 44
2

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];
}
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116