'Remove last comma in for loop using array

I'm stuck. I'm trying to remove the last comma at the back of the output but I just don't know how.

123, 97, 88, 99, 200, 50,

This is my code below, while checking for highest number in array.

public static void main(String[] args) {
    int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};

    for (int i : array) {
        if (i >= 50) {
            System.out.print(i + ", ");
        }
    }
    System.out.println();
}


Solution 1:[1]

One workaround here would be to prepend a comma to all but the first element in the array.

public static void main(String[] args) {
    int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};

    for (int i=0; i < array.length; ++i) {
        if (i > 0 && array[i] >= 50) {
            System.out.print(", ");
        }
        if (array[i] >= 50) {
            System.out.print(array[i]);
        }
    }
    System.out.println();
}

This prints:

97, 123, 88, 200, 50, 99

Edit:

For brevity, and for the sake of using Java's internal APIs which already handle your requirement, we could just use Arrays.toString directly:

int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};
String output = Arrays.toString(array).replaceAll("^\\[|\\]$", "");
System.out.println(output);
// 4, 97, 123, 49, 88, 200, 50, 13, 26, 99

Solution 2:[2]

Another solution, and to keep for-each statement:

public static void main(String[] args) {
    int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};

    boolean found = false;
    for (int i : array) {
        if (found) {
            System.out.print(", ");
        } else {
            found = true;
        }
        System.out.print(i);
    }
    System.out.println();
}

Solution 3:[3]

Here is another way you can do this. It makes use of the StringBuilder class:

int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};

StringBuilder sb = new StringBuilder("");
for (int i : array) {
    if (i >= 50) {
        if (!sb.toString().isEmpty()) {
            sb.append(", ");
        }
        sb.append(i);
    }
}
System.out.println(sb.toString());

Output to console window will be:

97, 123, 88, 200, 50, 99

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Maurice Perry
Solution 3 DevilsHnd