【问题标题】:How can I put my random values into an array in java?如何将我的随机值放入 java 中的数组中?
【发布时间】:2015-04-01 00:57:28
【问题描述】:

我正在制作一个对一组整数使用选择排序的程序,但我通过允许用户询问他们想要排序多少个整数以及他们是否想要输入整数或想要随机生成的整数。到目前为止,我已经编写了能够生成随机整数的程序,但我还没有让用户能够生成自己的数字。

如何获取这些随机生成的数字,并将它们放入一个数组中,以便我可以对这些值使用选择排序?

package sortingexcersices;

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

public class SortingExcersices {

    public static int myarray[], numOfElements, arrValues, n;

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.println("How many integers do you want to sort?");
        numOfElements = in.nextInt();

        myarray = new int[numOfElements];

        boolean found = false;

        do {

            System.out.println("If you would like random numbers, press 1.");
            System.out.println("If you would like to generate your own numbers, press 2.");

            n = in.nextInt();

            if (n == 1) {
                found = true;
            } else if (n == 2) {
                found = false;
            } else {
                System.out.println("Your input was invalid.");
            }

        } while (n != 1 && n != 2);

        if (found = true) {
            Random values = new Random();

            for (int i = 1; i <= myarray.length; i++) {
                arrValues = 1 + values.nextInt(50);
                System.out.print(arrValues + " ,");


            }
        }

    }
}

【问题讨论】:

    标签: java arrays sorting random selection


    【解决方案1】:

    数组在 Java 中是零索引的……你的 for 循环应该从 int i = 0 开始。然后你可以分配值:

    Random values = new Random();
    for (int i = 0; i < myarray.length; i++) {
        myarray[i] = values.nextInt(50);
    }
    

    然后通过调用Arrays.sort(myarray) 或在必要时实现自定义排序函数来实现排序。

    【讨论】:

    • 当我这样做时,我收到一条错误消息,指出线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 atsortingexcersices.SortingExcersices.main(SortingExcersices.java:42) 0 ,0 ,0 , Java 结果:1
    • 您确定将&lt;= 更改为&lt; 吗? ;)
    • 对不起,哈哈,你说得对,但是当我这样做时,我只会得到数组长度的 0,而不是随机数
    • 也许您需要包含一个检查以确保提供的numOfElements 大于0
    • ...归结为我在他之前一分钟写的内容,只是我没有包括语法错误。 ://
    【解决方案2】:
    for(int i = 0; i < myarray.length; i++){
     myarray[i] = 1 + values.nextInt(50);
     System.out.print(myarray[i] + " ,");
    }
    

    【讨论】:

    • 执行此操作时,我在线程 "main" java.lang.ArrayIndexOutOfBoundsException: 3 atsortingexcersices.SortingExcersices.main(SortingExcersices.java:42) 0 ,0 ,0 时收到错误异常,Java 结果: 1
    • myarray.length() 中的空括号给我一个错误,一旦我删除它们,我得到的值比我想要的少 1(如果我要求 5 个整数,它给我 4)
    • 你不想要 -1,
    • 是的,我真的很困惑。我检查了它。你不需要-1() 长度错误
    【解决方案3】:
    for (int i = 1; i <= myarray.length; i++) {
        arrValues[i] = 1 + values.nextInt(50); //you have to add the position
        System.out.print(arrValues + " ,");
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多