我正在制作一个对一组整数使用选择排序的程序,但我通过允许用户询问他们想要对多少个整数进行排序,以及他们是否想要输入整数或想要随机生成整数来使其变得更好。到目前为止,我已经编写了能够生成随机整数的程序,但我还没有让用户能够生成自己的数字。
我如何才能获取这些随机生成的数字,并将它们放入数组中,以便我可以对这些值使用选择排序?
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 中的数组是零索引的...您的 for 循环应该从 int i = 0
开始。然后您只需分配值即可:
Random values = new Random();
for (int i = 0; i < myarray.length; i++) {
myarray[i] = values.nextInt(50);
}
然后通过调用 Arrays.sort(myarray) 或在必要时实现自定义排序函数来实现排序。
关于java - 如何将我的随机值放入java中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29372009/