Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package AV7;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- public class FinalistTest {
- public static void main(String[] args) {
- FinalistPicker picker = new FinalistPicker(5);
- try {
- System.out.println(picker.pick(5));
- } catch (InvalidPickerArgumentsException e) {
- //e.getMessage();
- System.out.println(e.getMessage());
- }
- }
- }
- class InvalidPickerArgumentsException extends Exception {
- InvalidPickerArgumentsException(String msg) {
- super(msg);
- }
- }
- class FinalistPicker {
- int finalists;
- static Random RANDOM = new Random();
- public FinalistPicker(int finalists) {
- this.finalists = finalists;
- }
- public List<Integer> pick(int n) throws InvalidPickerArgumentsException {
- if (n > finalists) {
- throw new InvalidPickerArgumentsException("The number n cannot exceed the numer of finalists");
- }
- if (n <= 0) {
- throw new InvalidPickerArgumentsException("The number n has to be a positive number");
- }
- List<Integer> pickedFinalists = new ArrayList<>();
- while (pickedFinalists.size() != n) {
- int pick = RANDOM.nextInt(finalists) + 1;
- if (!pickedFinalists.contains(pick)) {
- pickedFinalists.add(pick);
- }
- }
- return pickedFinalists;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment