0

I need help organizing an array in java. The code below prints out random numbers in a straight line. However, I want the code to print out four of those numbers and then continue on a new line. Essential, I want the code to print out four random numbers on the first line, then another 4 random numbers on the second, and so on and so forth.

import java.util.Arrays;
import java.util.Random;

public class SelectionSort{ 

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] array = new int[200];

        Random rand = new Random();

        // for acsending order
        for (int i = 0; i < array.length; i++) 



        array[i] = rand.nextInt(1000000) + 1;
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        System.out.print("\n");


        // for descending order

        for (int i = array.length - 1; i >= 0; i--)
            System.out.print(array[i] + ", ");
    }

}
4
  • What do you want broken into 4-number lines: the ascending output, the descending output, or both? Commented Jul 5, 2018 at 3:26
  • 1
    StringBuilder, StringJoiner and/or String.format would be my recommendations Commented Jul 5, 2018 at 3:27
  • 1
    Please use curly braces around the for loop body, especially if you format the code like this. Commented Jul 5, 2018 at 3:29
  • Both, @TedHopp , and thank you for any help! Commented Jul 5, 2018 at 3:36

1 Answer 1

2

You need to print \n for each 4 numbers

import java.util.Arrays;
import java.util.Random;

public class SelectionSort { 

    public static void main(String[] args) {
        int[] array = new int[200];

        Random rand = new Random();

        // for acsending order
        for (int i = 0; i < array.length; i++) {

            array[i] = rand.nextInt(1000000) + 1;
        }

        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        System.out.print("\n");


        // for descending order

        for (int i = array.length - 1; i >= 0; i--) {
            System.out.print(array[i] + ", ");
            if (i % 4 == 0) { 
                // print \n for each 4 numbers.
                System.out.println("\n");
            }
        } 
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! but what if I also want the ascending output to be in four columns as well. Again, I appreciate the help!
@Sebastian - Use the same technique: an explicit loop with an index that you test. You can't use Arrays.toString(array) to do what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.