简体   繁体   中英

Store random integers in array

package selectionsortintro;

public class SelectionSortIntro {
    public static void main(String[] args) {
        int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };

        // print out unsorted list
        for (int count = 0; count < nums.length; count++) {
            System.out.print(nums[count] + " ");
        }
        System.out.println("\n---------------------------------");
        selectionSort(nums);

        // print out sorted list
        System.out.println("After sorting using the Selection Sort," + " the array is:");
        for (int count = 0; count < nums.length; count++) {
            System.out.print(nums[count] + " ");
        }
    }

    public static void selectionSort(int data[]) {
        int smallest;
        for (int i = 0; i < data.length - 1; i++) {
            smallest = i;
            // see if there is a smaller number further in the array
            for (int index = i + 1; index < data.length; index++) {
                if (data[index] < data[smallest]) {
                    swap(data, smallest, index);
                }
            }
        }
    }

    public static void swap(int array2[], int first, int second) {
        int hold = array2[first];
        array2[first] = array2[second];
        array2[second] = hold;
    }
}

I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :

int[] randomNumbers = new int[20];

Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome

EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?

Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.

  Scanner input = new Scanner(System.in);

    Scanner s = new Scanner(System.in);

    System.out.println("enter number of elements");

    int n = s.nextInt();

    int nums[]=new int[n];

    Random randomGenerator = new Random();



//print out unsorted list
for (int count = 0; count < nums.length; count++) {
  System.out.print(nums[count] + " ");
  nums[n] = randomGenerator.nextInt(1001);


}

Three different methods of generating random integers, from easiest to implement to hardest

To generate a random int [0, max)

(int)(Math.random() * max)

or use

Random r = new Random();
r.nextInt(max);

A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)

You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop

Adding an option to set the size of the array based off of user input is a bit more tricky

The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method

Another way to read input is the Scanner class

Whichever way you choose, you may end up with a String variable you need to convert to an int with

String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);

Here's an example using a traditional array and a JOptionPane:

import javax.swing.*;
import java.util.Random;

public class Random_int_array {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Total number of integers");
        int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));

        int[] array = new int[iTotalCount];

        Random randomGenerator = new Random();

        for(int i=0; i < iTotalCount; i++){
            array[i] = randomGenerator.nextInt(1001);
        }

        // Now you can do whatever processing you would like to do
        // For the sake of this answer, I will just print the numbers

        for(int i=0; i < array.length; i++){
            System.out.println(array[i]);
        }

        // We should explicitly call exit because we used a form/window
        System.exit(0);
    }
}

And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;

import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;

public class Random_int_array {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Total number of integers");
        int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));

        // Can also be written as: ArrayList<Integer> array = new ArrayList<>();
        // in newer versions of Java.
        ArrayList<Integer> array = new ArrayList<Integer>();

        Random randomGenerator = new Random();

        for(int i=0; i < iTotalCount; i++){
            array.add(randomGenerator.nextInt(1001));
        }

        // Now you can do whatever processing you would like to do
        // For the sake of this answer, I will just print the numbers

        for(int i=0; i < array.size(); i++){
            System.out.println(array.get(i));
        }

        // We should explicitly call exit because we used a form/window
        System.exit(0);
    }
}

Note: ArrayList s cannot use primitive data types, so you must specify it as using an Integer rather than an int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM