Advertisement
ivana_andreevska

AV7 Finalisti

Aug 15th, 2022
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. package AV7;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Random;
  6.  
  7. public class FinalistTest {
  8.     public static void main(String[] args) {
  9.         FinalistPicker picker = new FinalistPicker(5);
  10.         try {
  11.             System.out.println(picker.pick(5));
  12.         } catch (InvalidPickerArgumentsException e) {
  13.             //e.getMessage();
  14.             System.out.println(e.getMessage());
  15.         }
  16.     }
  17.  
  18. }
  19.  
  20. class InvalidPickerArgumentsException extends Exception {
  21.     InvalidPickerArgumentsException(String msg) {
  22.         super(msg);
  23.     }
  24.  
  25. }
  26.  
  27. class FinalistPicker {
  28.     int finalists;
  29.     static Random RANDOM = new Random();
  30.  
  31.     public FinalistPicker(int finalists) {
  32.         this.finalists = finalists;
  33.     }
  34.  
  35.     public List<Integer> pick(int n) throws InvalidPickerArgumentsException {
  36.         if (n > finalists) {
  37.             throw new InvalidPickerArgumentsException("The number n cannot exceed the numer of finalists");
  38.         }
  39.         if (n <= 0) {
  40.             throw new InvalidPickerArgumentsException("The number n has to be a positive number");
  41.         }
  42.  
  43.         List<Integer> pickedFinalists = new ArrayList<>();
  44.  
  45.         while (pickedFinalists.size() != n) {
  46.             int pick = RANDOM.nextInt(finalists) + 1;
  47.             if (!pickedFinalists.contains(pick)) {
  48.                 pickedFinalists.add(pick);
  49.             }
  50.         }
  51.         return pickedFinalists;
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement