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("]");
}
}
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.
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 .
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("]");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With