Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

guys I was wondering how to remove the extra comma and space from the array? When I run the program it gives me {1, 2, 3, 4, 5, }. What I want is {1, 2, 3, 4, 5}. Main must stay the same. PrintArray method is the one I need help with.

Referring to duplicate question statement. This is different because it asks a user for a number and prints the array accordingly. This is not a duplicate question.

    public static void printArray(int[] myArray)
    {

        System.out.print("[");
        for(int i = 0; i < myArray.length; i++)
        {
            myArray[i] = i + 1;
            System.out.print(myArray[i] + ", ");
        }
        System.out.println("]");
    }
}
like image 680
IDK Avatar asked Apr 12 '17 22:04

IDK


People also ask

How do you remove the last entry in an array in Java?

We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element.

How do you remove leading and trailing commas in Java?

Using the substring() method We remove the last comma of a string by using the built-in substring() method with first argument 0 and second argument string. length()-1 in Java. Slicing starts from index 0 and ends before last index that is string. length()-1 .


1 Answers

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("]");
}
like image 186
John3136 Avatar answered Oct 23 '22 01:10

John3136