Wednesday, June 20, 2018

How to remove last comma and space in array? Java




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("]");
}

}

Answer



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("]");
}


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...