Reputation: 15
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] + ", ");
}
}
Upvotes: 0
Views: 79
Reputation: 46
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");
}
}
}
}
Upvotes: 2