Home > database >  Want to create array of random integers in ascending order
Want to create array of random integers in ascending order

Time:04-05

I am currently working on a simple program where you're asked "How many random numbers between 0 - 999 do you want?" You enter a value (lets say 3), and it prints "Here are your numbers:" "213 52 821". How do I go about making the random numbers print in ascending order, from smallest to biggest. I don't want you to write the code for me, just some pointers.

I am really new to programming

import java.util.Scanner;
import java.util.Random;

public class Main {
    public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);                                                    
    System.out.print("How many random numbers between 0 - 999 do you want? ");     
    int value = scan.nextInt(); 
    System.out.println("Here are your numbers:");

    int randomArray[]=new int[value]; 

    for(int i = 0; i<value; i  )
    {   
        randomArray [i] = (int) (Math.random () * 999); 
        System.out.println(randomArray[i]);
    }   
}  
}

CodePudding user response:

Seems like you have done most of the work. You just need to sort the resulting array.

Use Arrays.sort(randomArray) to sort the array.

Edit: You can print the array outside for-loop with System.out.println(Arrays.toString(randomArray));

Edit 2: In response to your comment, replace the for-loop with this code:

for(int i = 0; i<value; i  )
{   
    randomArray [i] = (int) (Math.random () * 999);
}  
Arrays.sort(randomArray);
System.out.println(Arrays.toString(randomArray));

Edit 3: Replace the for loop in you code with this code if you want both ascending and descending order.

int[] ascendingArray = randomArray.clone();
Arrays.sort(ascendingArray);
int[] descendingArray= ascendingArray.clone();
Collections.reverse(Arrays.asList(descendingArray));

// These two lines print the random array in ascending order.
System.out.println("Sorted array (ascending order):");
System.out.println(Arrays.toString(ascendingArray));

// These two lines print the random array in descending order.
System.out.println("Sorted array (descending order):");
System.out.println(Arrays.toString(descendingArray));

CodePudding user response:


import java.util.Scanner;

import java.util.*;

public class Main {

    public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in); 
                                                   
    System.out.print("How many random numbers between 0 - 999 do you want? "); 
    
    int value = scan.nextInt(); 
    System.out.println("Here are your numbers:");
    int randomArray[]=new int[value]; 
    for(int i = 0; i<value; i  )
    {   
        randomArray [i] = (int) (Math.random () * 999); 

        //System.out.println(randomArray[i]);
    } 

   Arrays.sort(randomArray);

   System.out.println(randomArray.toString());  

  } 
}
  •  Tags:  
  • java
  • Related