How to remove last comma and space in array? Java [duplicate]

Don’t print it in the first place. Print the comma before the string and only when i > 0.

public static void printArray(int[] myArray)
{

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

Leave a Comment