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