gpt4 book ai didi

java - 生成介于 0 和 y 之间的随机数,x 是在 java 中生成的数量

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:17:41 25 4
gpt4 key购买 nike

我需要帮助生成 0 和 y 之间的随机数,x 是在 java 中生成的数量,正如您所看到的,我几乎就在那里,但是最后对它们进行排序给我带来了麻烦,请帮助我纠正这个问题!

   //imports
import java.util.Scanner;
import java.util.Random;
//Class
public class RandomGen {
//Main Method
public static void main(String[] args) {
//Prepare Scanner
Scanner randomScanner = new Scanner(System.in);

System.out.println("Between 0 and what integer would you like to generate random Integers? ");
int y = randomScanner.nextInt();

System.out.println("Please Specify the number of Random integers you would like:");
int x= randomScanner.nextInt();

Random pseudo = new Random();
//Initialize Random
for(int i =0; i<x; i++) {

System.out.println(pseudo.nextInt(y+1));


}

}

}

//这段代码生成随机数就好了!现在我需要对它们进行分类!//这几行下面的代码语法错误太多//我可以在上面的代码中添加什么来使其成为//此信息的简单组织,我需要创建一个数组然后将其组织起来。//下面是我失败的尝试,谁能保持上面的代码简单?

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

public class RandomInt {

public static void main(String[] args) {

int[] increasingRandoms(int x, int y);
{

//establishing an array

Scanner randomScanner = new Scanner(System.in);

System.out.println("Between 0 and what integer would you like to generate random Integers? ");
y = randomScanner.nextInt();

System.out.println("Please Specify the number of Random integers you would like:");
x= randomScanner.nextInt();

//Setting x to pseudoRandom into an array in order to sort later
int[] pseudoRandom = new int [x];


for(int i =0; i< x; i++){

Random pseudo = new Random();

pseudoRandom[i] = pseudo.nextInt(y);
}
//returning an array in ascending order
Arrays.sort(pseudoRandom);
return pseudoRandom;
}

for(int number : increasingRandoms(y, x)) {
System.out.print(number + " ");
}
}
}

最佳答案

尝试先将 increasingRandoms(x,y) 返回的数组存储在一个变量中,然后在增强的 for 循环中使用该变量,而不是直接使用该方法。

int[] temp=increasingRandoms(y, x);
for(int number : temp) {
System.out.print(number + " ");
}

此外,我不明白为什么你应该在每次循环迭代时创建一个新对象,最好在进入循环之前创建一个 Random 对象,然后在循环中调用 nextInt(int)

   int[] pseudoRandom = new int [x];


Random pseudo = new Random();

for(int i =0; i< x; i++){

pseudoRandom[i] = pseudo.nextInt(y);
}

关于java - 生成介于 0 和 y 之间的随机数,x 是在 java 中生成的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32930238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com