user7214683 user7214683 - 10 days ago 5
Java Question

Stop extra comma and space from being printed out at end of each array

This has been driving me crazy all day. I've been trying to get the arrays to stop printing a comma after the last number that's printed for that array. I just can't seem to get it to work properly. Any help at all would be greatly appreciated.

This is the output of the arrays:


[5, 6, 7, 8, ]

[[2, 4, 6, 8, ] [8, 7, 9, 1, ] [35, 1, 2, ]]

[[12, ] [3, 4, 5, ] [6, ] [7, 8, 9, ]]


The output I want:


[5, 6, 7, 8]

[[2, 4, 6, 8] [8, 7, 9, 1] [3, 5, 1, 2]]

[[1, 2] [3, 4, 5] [6] [7, 8, 9]]


public class ArrayPrinter {

public static void main(String[] args) {
int[] oneD = {5 ,6 ,7 ,8};

int[][] twoD = {{2, 4, 6, 8}, {8, 7, 9, 1}, {3, 5, 1, 2}};

int[][] twoD2 = {{1, 2}, {3, 4, 5}, {6}, {7, 8, 9}};

printArray(oneD);
printArray(twoD);
printArray(twoD2);

}

public static void printArray(int[] arr)
{
int l = arr.length;
System.out.print("[");
for (int i = 0; i < l; i++)
{
if (arr [i] == l-1)
System.out.print(arr[i]);

else
System.out.print(arr[i] + ", ");
}

System.out.println("]");

}

public static void printArray(int[] [] arr)
{

int l = arr.length;
System.out.println("[");
for (int i=0; i < l; i++)
printArray(arr[i]);
System.out.println("]");
}
}

Answer

If you only want to print a comma after each element that is not the last, you want to check its position, not its value:

if ( i < l-1 )
   System.out.print(arr[i] + ", ");
else
   System.out.print(arr[i]);