Reputation:
I'm trying to print 10,000 random numbers in ascending and descending order using Arrays.sort then output it. If I try it as this, it does not give the right output.
import java.util.*;
import java.util.Random;
public class QuestionFour
{
public static void main(String[] args)
{
int arr[] = new int[10000];
Random rand = new Random();
for (int i=0; i<10000; i++)
{
arr[i] = rand.nextInt( 100 ) + 1;
Arrays.sort(arr);
System.out.println(arr);
}
}
}
Upvotes: 0
Views: 322
Reputation: 54168
Arrays.sort()
does not have anything related with output, it only sorts
an array
Let your loop fill the array, and after that sort
and print
it with Arrays.toString()
int arr[] = new int[10000];
Random rand = new Random();
for (int i=0; i<10000; i++){
arr[i] = rand.nextInt( 100 ) + 1;
}
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
Reverse order sort :
You could use Arrays.sort(arr, Comparator.reverseOrder());
, but this requires an array of objects, it would requires a Integer arr[] = new Integer[10000];
rather than int
Use a List<Integer>
instead of en array, it would be easier to manipulate
List<Integer> list = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 10000; i++) {
list.add(rand.nextInt(100) + 1);
}
list.sort(Comparator.reverseOrder());
System.out.println(list); //[100, 100, 100, 100, 100, 100, 100, 100 ...
Upvotes: 1
Reputation: 1475
you need to put Arrays.sort(arr);
outside your for loop and create another loop for printing the array after it had been sorted.
your code should be as follows :
import java.util.*;
import java.util.Random;
public class QuestionFour
{
public static void main(String[] args)
{
int arr[] = new int[10000];
Random rand = new Random();
for (int i=0; i<10000; i++)
{
arr[i] = rand.nextInt( 100 ) + 1;
}
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Upvotes: 1