这是我上一个问题的后续问题。使用这段代码,我想知道如何从1到56生成4个不同的随机数,对于no情况,从1到51相同,如果这两种情况都没有使用,则循环回到开始for。
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;
}
}
}
}
发布于 2018-12-04 01:27:14
我不确定你在问什么,但这应该会使4个随机数达到56个。
Random rand = new Random();
int[] nums = new int[4];
for (int i = 0; i < 4; i++) {
int[i] = rand.nextint(57);
}
发布于 2018-12-04 01:29:27
您可以创建一个方法来避免重复代码。
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的数字:
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语句:
for (int i = 1; i <= 4; i++) {
numbers.add(obtainRandomNumberInRange(100, 200));
}
发布于 2018-12-04 02:01:56
我不知道你要做什么,但是你可以使用下面的代码
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);
}
通过这种方法,你永远不会得到重复的数字,我希望你能理解。
https://stackoverflow.com/questions/53598704
复制相似问题