[英]Random Numbers within a Range
在任何情況下,都可以使用此工具生成倉位定單。
但是,我遇到了無限循環。 我怎樣才能解決這個問題?
import java.util.Random;
import java.util.Scanner;
public class WhoGoesFirst {
public static void main(String args[]) {
Random random = new Random();
Scanner input = new Scanner(System.in);
int MIN = 1;
int students = 0;
System.out.print("How many students do you have?");
students = input.nextInt();
int comp = random.nextInt(students - MIN + 1) + MIN;
for (int number = 0; number <= students; comp++) {
System.out.println(random);
}
}
}
在循環中增加您的數字變量,它應該可以解決此問題:
for (int number = 0; number <= students; number++, comp++) {
System.out.println(comp); //random is an object
}
您需要增加數字:
import java.util.Random;
import java.util.Scanner;
public class WhoGoesFirst {
public static void main(String args[]) {
Random random = new Random();
Scanner input = new Scanner(System.in);
int MIN = 1;
int students = 0;
System.out.print("How many students do you have?");
students = input.nextInt();
int comp = random.nextInt(students - MIN + 1) + MIN;
for (int number = 0; number <= students; number++) {
System.out.println(random);
comp++;
}
}
}
看這行:
System.out.println(random);
此實現嘗試打印隨機數生成器,而不是數字本身。 使用內置的Collections.shuffle有一個更簡單的解決方案:
List<Integer> positions = new ArrayList<Integer>(students);
for (int number = 0; number < students; number++)
positions.add(number);
Collections.shuffle(positions);
for (Integer number : positions)
System.out.println(number);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.