如何以随机顺序打印给定范围内的数字

时间:2015-10-16 14:23:42

标签: java random numbers

如何在给定范围内打印数字。示例:10 - 13按随机顺序(10 12 13 11)?

public class RandomizeNumbers {
    public static void main(String[] args) {
        Scanner getInput = new Scanner(System.in);
        int minimum = getInput.nextInt();
        int maximum = getInput.nextInt();
        Random t = new Random();

        for (int i = minimum; i <= maximum; i++) {
            System.out.println(t.nextInt(i));
        }
    }
}

3 个答案:

答案 0 :(得分:4)

填写包含必要项目的列表并使用Collections.shuffle()对其进行随机播放,然后打印:

List<Integer> c = new ArrayList<>();
for (int i = start; i <= end; i++)
   c.add(i);
Collections.shuffle(c);
System.out.println(c);

答案 1 :(得分:0)

只是为了知识,你不能使用这种方法,

new Random().ints(start, endExclusive).distinct().limit(quantity).boxed().forEach(System.out::println);

Obs:你需要java 8才能使用它。

答案 2 :(得分:0)

使用Java 8 IntStream,它就像:

一样简单
IntStream.rangeClosed(minimum, maximum).map(i -> t.nextInt(i))
                .forEach(System.out::println);

用法:

import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;

public class RandomNumbers {
    public static void main(String[] args) {
        Scanner getInput = new Scanner(System.in);
        int minimum = getInput.nextInt();
        int maximum = getInput.nextInt();

        Random t = new Random();
        IntStream.rangeClosed(minimum, maximum).map(i -> t.nextInt(i))
                .forEach(System.out::println);

        getInput.close();
    }
}