【问题标题】:Store random integers in array在数组中存储随机整数
【发布时间】:2015-10-26 20:42:37
【问题描述】:
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;
    }
}

我想将随机数量的随机整数添加到数组中,因此选择排序算法会将它们排序出来。唯一的问题是,我不知道如何用随机数存储数组而不是固定数量。如果这令人困惑,那么当你制作数组时就像:

int[] randomNumbers = new int[20];

其中 20 是生成的数字数量。好吧,我想让用户判断有多少数字随机生成到数组中。所以我在想也许使用 ArrayList?但是,我对如何使用它将随机数添加到自身感到困惑。如果有人可以帮助我,那就太棒了

编辑:所以我使用扫描仪获得输入,但我真的更喜欢 JOptionPane,因为输入对话框看起来更好,但如果扫描仪是唯一的方法,那很好。所以现在已经完成了,我只需要用随机整数实际填充数组,有人知道怎么做吗?

这就是我想出的,我的代码出错了,如果有人能提供帮助,那就太棒了。

  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);


}

【问题讨论】:

  • 我想让用户判断随机生成多少个数字到数组中:然后首先询问用户他想要多少个数字,然后只创建一个适当大小的数组:用户输入的大小。
  • @JBNizet 这就是我的部分大脑,我不知道如何写出数组,所以它不是固定数量,而是需要用户输入。我收到投射和类型错误。

标签: java arrays random


【解决方案1】:

这是一个使用传统数组和 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);
    }
}

这是一个使用带有 JOptionPane 的 ArrayList 而不是常规的 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);
    }
}

注意:ArrayLists 不能使用原始数据类型,因此您必须将其指定为使用 Integer 而不是 int。

【讨论】:

  • 谢谢,这对我帮助很大!现在可以了,谢谢大家的回答,你们都很棒。该线程现已解决。
【解决方案2】:

添加一个选项来根据用户输入设置数组的大小有点棘手

最简单的编码方式是传入命令行参数,然后在 main 方法的 args 变量中读取它们

另一种读取输入的方法是 Scanner 类

无论您选择哪种方式,您最终都可能会得到一个需要将其转换为 int 的 String 变量

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

【讨论】:

  • 感谢您的建议。我宁愿使用 JOptionPane.showInputDialog 因为它看起来好多了,还有可能吗?扫描仪工作正常,但如果你明白我的意思,我想要一个更好的外观。另外,既然我已经开始工作了,我只需要用随机数填充我的数组,我试图将数组分配给我的随机数变量,但我得到了错误。
  • 查看我的其他答案以填充您的数组 - 使用 for(int i = 0; i &lt; nums.length; i++) nums[i] = (random number)。如果你想使用swing(JOptionPane)来输入东西,请随时给我发一条消息,我回家后会输入它,它......有点复杂。现在查看docs.oracle.com/javase/tutorial/uiswing
【解决方案3】:

生成随机整数的三种不同方法,从最容易实现到最难实现

生成一个随机的 int [0, max)

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

或使用

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

一种更复杂的生成随机数而不是 Java 的伪随机生成器的方法是查询 random.org 的数据。请注意,这可能需要更长的时间来设置和编码,以及依赖第三方服务器(无论它们多么可靠)

您可以使用随机 int 以随机长度初始化输入数组,然后使用 for 循环用随机数填充值

【讨论】:

  • 为什么不使用 Random.nextInt(max)?更简单,更合适。
  • Random 有静态方法吗?我习惯于将它初始化为多线程,并使用 Math.random() 进行单线程
  • 与其投反对票和保持沉默,不如说出为什么/如何使答案更好
  • JB Nizet 已经解释了如何让它变得更好,我赞成他的评论。如果您编辑您的答案,请对我发表评论,我会对其进行审核。
  • @erickson 甚至添加了第三种生成随机数的方式,但是对于像这样的单线程问题,过度复杂/混乱代码没有多大意义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
  • 2022-01-12
  • 2014-04-05
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
相关资源
最近更新 更多