[Solved] Generating and sorting a sequence of 20 numbers in an array w/ for loop (Java)


You already import java.util.Arrays why not use that to print out the sequence?

Note: I removed the unnecessary import of java.util.Random (you can use revert back to using that if you want, and whatever num was for as I think that made everything more complicated than required.

import java.util.Arrays;

public class problem1 {
  public static void main(String[] args) {

    int[] sequence = new int[20];

    //Generates 20 Random Numbers in the range 1 to 99
    for(int i = 0; i < sequence.length; i++)
      sequence[i] = (int)(Math.random() * 99 + 1);

    System.out.println("The sequence is: " + Arrays.toString(sequence));

    //Sort the sequence
    Arrays.sort(sequence);

    System.out.println("The sorted sequence is: " + Arrays.toString(sequence));
  }
}

Example Output:

The sequence is: [10, 25, 94, 61, 59, 14, 64, 90, 28, 54, 29, 17, 71, 74, 95, 9, 56, 46, 44, 57]
The sorted sequence is: [9, 10, 14, 17, 25, 28, 29, 44, 46, 54, 56, 57, 59, 61, 64, 71, 74, 90, 94, 95]

Try it here!

2

solved Generating and sorting a sequence of 20 numbers in an array w/ for loop (Java)