我正在制作一个程序,对一组整数使用选择排序,但我通过允许用户询问他们想要排序多少整数,以及他们是否想要输入整数或想要随机生成的整数。我已经将程序编码为能够生成随机整数,但我还没有让用户能够生成自己的数字。
我如何能够获取这些随机生成的数字,并将它们放入数组中,以便我可以对这些值使用选择排序?
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 + " ,");
}
}
}
}
答案 0 :(得分:0)
在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)
或在必要时实现自定义排序功能来实现排序。
答案 1 :(得分:0)
for(int i = 0; i < myarray.length; i++){
myarray[i] = 1 + values.nextInt(50);
System.out.print(myarray[i] + " ,");
}
答案 2 :(得分:0)
for (int i = 1; i <= myarray.length; i++) {
arrValues[i] = 1 + values.nextInt(50); //you have to add the position
System.out.print(arrValues + " ,");
}