首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我如何获得一个代码来生成从1到56的4个不同的随机数?

我如何获得一个代码来生成从1到56的4个不同的随机数?
EN

Stack Overflow用户
提问于 2018-12-04 01:18:42
回答 3查看 53关注 0票数 0

这是我上一个问题的后续问题。使用这段代码,我想知道如何从1到56生成4个不同的随机数,对于no情况,从1到51相同,如果这两种情况都没有使用,则循环回到开始for。

代码语言:javascript
复制
import java.util.Scanner;

public class RandomPerkSelector {

public static void main(String [] args){
Scanner userInputReader = new Scanner(System.in);
System.out.println("Are you playing as a survivor?");
while(true){
String userInput = userInputReader.nextLine();
if(userInput.equals("Yes")){
   //"Yes" case
   //generate your numbers for "Yes"
   break;
}else if(userInput.equals("No")){
   //"No" case
   //generate your numbers for "No"
   break;
}else{
   System.out.println("This is a yes or no question.");
   continue; 
   }
  }
 }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-12-04 01:27:14

我不确定你在问什么,但这应该会使4个随机数达到56个。

代码语言:javascript
复制
Random rand = new Random();
int[] nums = new int[4];
for (int i = 0; i < 4; i++) {
    int[i] = rand.nextint(57);
}
票数 1
EN

Stack Overflow用户

发布于 2018-12-04 01:29:27

您可以创建一个方法来避免重复代码。

代码语言:javascript
复制
    private static int obtainRandomNumberInRange(int min, int max) {
        if (min >= max) {
            throw new IllegalArgumentException("Min in greater than Max value");
        }

        Random r = new Random();
        return r.nextInt((max - min) + 1) + min;
    }

这将返回一个介于min和max之间的int值。您可以使用此方法,并根据需要调用它。

例如,如果您正在生成表示yes的数字:

代码语言:javascript
复制
List<Integer> numbers = new ArrayList<Integer>();
//This will call the function 4 times, and get numbers between 100 and 200. 
IntStream.range(0, 4).forEach(x-> numbers.add(obtainRandomNumberInRange(100, 200)));

现在这些数字有4个介于100和200之间的随机数。

或者,您可以使用for语句:

代码语言:javascript
复制
for (int i = 1; i <= 4; i++) {
       numbers.add(obtainRandomNumberInRange(100, 200));
}
票数 0
EN

Stack Overflow用户

发布于 2018-12-04 02:01:56

我不知道你要做什么,但是你可以使用下面的代码

代码语言:javascript
复制
int n = 2 * (Integer.MAX_VALUE / 3);
int low = 0;
for (int i = 0; i < 4; i++)
if (random(n) < n/2) {
    low++;
 System.out.println(low);
 }

通过这种方法,你永远不会得到重复的数字,我希望你能理解。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53598704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档