简体   繁体   English

将随机整数存储在数组中

[英]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]; int [] randomNumbers =新的int [20];

Where 20 is the amount of numbers generated. 其中20是生成的数字量。 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? 所以我在想也许使用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. 编辑:所以我使用扫描仪输入,但是我真的更喜欢JOptionPane,因为输入对话框看起来好多了,但是如果扫描仪是唯一的好方法。 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) 生成随机整数[0,最大值)

(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. 代替Java的伪随机数生成器,生成更多随机数的一种更复杂的方法是查询random.org以获取数据。 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 您可以使用random int初始化具有随机长度的输入数组,然后使用for循环用随机数填充值

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 最简单的编码方法是传入命令行参数,然后在main方法的args变量中读取它们

Another way to read input is the Scanner class 读取输入的另一种方法是Scanner类

Whichever way you choose, you may end up with a String variable you need to convert to an int with 无论选择哪种方式,最终都可能需要将String变量转换为int

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

Here's an example using a traditional array and a JOptionPane: 这是一个使用传统数组和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; 这是一个使用ArrayList和JOptionPane代替常规int[] array;的示例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 . 注意: ArrayList不能使用原始数据类型,因此必须将其指定为使用Integer而不是int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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