freshwaterjoe
freshwaterjoe

Reputation: 101

Printing an array in a table format

I have an array filled with 50 numbers and cannot figure how to output the array into a table like format.

Currently when I print my array it is being outputted into one long line of numbers, and what I am aiming for is 10 lines, each consisting of 5 numbers.

Furthermore I would prefer each value to be a 3 digit value. So 1 would be represented as 001, to improve readability and presentation.

import java.util.*;
public class Random50 {
    public static void main (String[] args)
    {
        final int MAX_SIZE = 50;
        int[] r50 = new int[MAX_SIZE];

        Random rand = new Random();

        for (int i=0; i<r50.length; i++)
        {   
            r50[i] = rand.nextInt(1000);

            for (int j=0;j<i;j++)
            {               
                if (j!=i && r50[i] == r50[j])
                {
                    System.out.println("Duplicate: " + r50[i]);
                    r50[i] = rand.nextInt(1000);
                }

            }
        }

        System.out.printf(Arrays.toString(r50));

    }

}

Upvotes: 0

Views: 3250

Answers (1)

Andrew_CS
Andrew_CS

Reputation: 2562

You really should only ask 1 question per post so I'll answer your first question - it makes it so other users can find relevant information in the future (not trying to be mean).

If you want to start printing on a new line every fifth number you could make use of the modulus operator %.

for(int i = 0; i < 50; i++){
    if(i % 5 == 0){ // True every fifth value
        System.out.print("\n"); // Print a new line
    }

    ... // Your other code goes here
}

Upvotes: 1

Related Questions