How can I print numbers in given range. Example: 10 - 13 in randomized order (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));
}
}
}
Fill up a list with necessary items and shuffle them using Collections.shuffle()
, then print:
List<Integer> c = new ArrayList<>();
for (int i = start; i <= end; i++)
c.add(i);
Collections.shuffle(c);
System.out.println(c);
Just for knowledge, you must not use this approach,
new Random().ints(start, endExclusive).distinct().limit(quantity).boxed().forEach(System.out::println);
Obs: you need java 8 to use it.
Using Java 8 IntStream , it is as simple as:
IntStream.rangeClosed(minimum, maximum).map(i -> t.nextInt(i))
.forEach(System.out::println);
Usage:
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.