0

I am trying to make displayArray look like an array, but I can't figure it out. It prints out this:

[7, 8, 9 , 0, 9, 0, ]

Instead of this:

[7, 8, 9, 0, 9, 0]

I know that the problem is because of

System.out.print(b + ", ");

but I don't know what else to do.

import java.util.*;
public class changeUp 
{
    public static void main(String[] args) 
    {
        int[] arr = new int[6]; 
        populateArray(arr);
        displayArray(arr);
    }
    private static void populateArray(int[] arr)
    {
        Random r = new Random();
        Scanner console = new Scanner(System.in); 
        for(int i = 0; i < 6; i++){
            int ranInd = r.nextInt(6);
            System.out.print("Enter a value: ");
            arr[ranInd] = console.nextInt();
        }
    }
    private static void displayArray(int[] arr)
    {
        System.out.print("[");
        for(int b : arr)
        {
            System.out.print(b + ",  ");
        }
        System.out.println("]");
    }  
}
ineedhelp
  • 65
  • 4

1 Answers1

1

You print ", " on the last iteration of displayArray() for loop.

To avoid this add index check:

private static void displayArray(int[] arr)
{
    System.out.print("[");
    for(int i = 0; i < arr.length; i++)
    {
        int b = arr[i];
        System.out.print(b);

        if(i < arr.length - 1) {
            System.out.print(", ");
        }
    }
    System.out.println("]");
}

Output:

Enter a value: 4
Enter a value: 4
Enter a value: 4
Enter a value: 4
Enter a value: 4
Enter a value: 4
[4, 4, 0, 4, 0, 4]
vszholobov
  • 2,133
  • 1
  • 8
  • 23