范围内的随机数

时间:2016-02-10 22:41:10

标签: java for-loop random

这是一个可用于在任何情况下生成头寸订单的工具。

但是,我遇到了无限循环。我该如何解决这个问题?

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);
        }
    }
}

3 个答案:

答案 0 :(得分:4)

增加循环中的数字变量,它应该解决问题:

{{1}}

答案 1 :(得分:2)

您需要增加数字:

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++;
        }
    }
}

答案 2 :(得分:1)

看看这一行:

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);