如何将randomNumbers的值转换为数组集,以便我可以将它们用于以后的排序?
这是我的主要课程
import java.util.Arrays;
import java.util.*;
public class Main {
public static void main(String[] args){
int choice;
int g;
Scanner input=new Scanner(System.in);
System.out.println("Enter how many random no:");
g=input.nextInt();
RandomAlgo ran=new RandomAlgo();
g=ran.randomNum(g);
RandomAlgo rand=new RandomAlgo();
int[] data=rand.randomNum(randomNumbers); //did i did this right here?
System.out.println("Choose Sorting algorithm: \n (1)Selection Sort \n (2)Insertion Sort \n (3)Bubble Sort \n (4)Quick Sort" );
choice=input.nextInt();
switch(choice){
case 1:{
SortingAlgo algo=new SortingAlgo();
data=algo.selectionSort(data);
break;
}
我的随机数课这里是我的代码。我的问题是如何将randomNumbers
的值传递给我的主类?
public class RandomAlgo extends Main{
public int randomNum(int g){
Random rand = new Random();
int e;
int i;
HashSet<Integer> randomNumbers = new HashSet<Integer>();
for (i = 0; i < g; i++) {
e = rand.nextInt(1000);
randomNumbers.add(e);
if (randomNumbers.size() <= 0) {
if (randomNumbers.size() == 0) {
g = g;
}
g++;
randomNumbers.add(e);
}
}
System.out.println("Random numbers Are : " +randomNumbers);
return g;
}
}
答案 0 :(得分:2)
int [] data = rand.randomNum(randomNumbers); //我这样做了吗?
randomNumbers
是子类RandomAlgo.randomNum()
的局部变量,Main
不知道它。
您可以按照以下方式撰写RandomAlgo
。
public class RandomAlgo { // Why extend Main ???
public int[] randomNum(int g){ // return an int array with random numbers instead
Random rand = new Random();
int[] randomNumbers = new int[g];
for (int i = 0; i < g; i++) {
int e = rand.nextInt(1000);
randomNumbers[i] = e;
// if (randomNumbers.size() <= 0) {
// if (randomNumbers.size() == 0) {
// g = g;
// }
// g++;
// randomNumbers.add(e);
// }
}
// System.out.println("Random numbers Are : " +randomNumbers);
return randomNumbers;
}
}
您必须相应地更改Main
,
public class Main {
public static void main(String[] args){
int choice;
int g;
Scanner input=new Scanner(System.in);
System.out.println("Enter how many random no:");
g=input.nextInt();
// RandomAlgo ran=new RandomAlgo();
// g=ran.randomNum(g);
RandomAlgo rand=new RandomAlgo();
int[] data=rand.randomNum(g); // load return random numbers array to data
System.out.println("Choose Sorting algorithm: \n (1)Selection Sort \n (2)Insertion Sort \n (3)Bubble Sort \n (4)Quick Sort" );
choice=input.nextInt();
答案 1 :(得分:1)
randomNum()
正在返回您最初请求的随机数的号,而不是数字本身。将randomNum()
的返回类型更改为int[]
并在方法内部,将g
HashSet转换为数组,可能使用其中一种方法described here,然后返回该数组。