Hi i am writing a lottery method where the user has to enter in two numbers, n and k, as arguments. The lottery gets filled with a randomized queue that goes up to k. so if i put in k=10 the queue would hold 1,2,3,4,5,6,7,8,9,10. The argument n is the number of items that has to be removed randomly. so if i chose 3 then it could return 4,6,8 or it could be 1,3,10.
Now if n is greater than k it has to throw an error saying that there is not enough items in the queue to pull. So if i put n=5 and k=3, there are still 3 items in the queue but i can't select 5.
Now my problem is i have to return the items that are still in the queue. so n=5 and k=3 would return 1,3,2 or 2,3,1 and so forth. But i have to print an exception after i return that array. So far i am able to return the array but i can not get the try catch exception to work. Is there another method i can try that will return the array and then print out the exception after that so it looks like this:
%java Lottery 5 2 2 1 java.lang.Exception: Not enough items in your queue. at Lottery.pickNumbers(Lottery.java:29) at Lottery.main(Lottery.java:56)
Here is my code
import java.util.*; import java.math.*; public class Lottery{ RandomizedQueue rq; Random Rnum = new Random(); int [] Larray; // constructs a Lottery class public Lottery(){ } // picks the numbers and store them in an array of integers // int n: number of items to pick // int k: maximum integer to be picked public int [] pickNumbers(int n, int k) throws Exception{ rq = new RandomizedQueue(); int [] remainQueue = new int [k]; if(n>k) { for(int i=1; i<=remainQueue.length;i++) { rq.enqueue(i); } for(int i =0; i<remainQueue.length;i++) { try{ remainQueue[i] = rq.dequeue(); } catch (Exception e) { System.out.println("not enough items in the queue"); } } return remainQueue; } for(int i =1;i<=k;i++) { rq.enqueue(i); } Larray = new int[n]; for(int i = 0;i< Larray.length;i++) { Larray[i] = rq.dequeue(); } return Larray; } // Do not change main(). public static void main(String [] args) throws Exception{ if (args.length<2){ System.out.println("Please enter your input values."); System.out.println("e.g. java Lottery [number of integers to pick] [Maximum integer to be picked]"); }else{ int n = Integer.parseInt(args[0]); int k = Integer.parseInt(args[1]); Lottery l = new Lottery(); try{ int [] picked = l.pickNumbers(n,k); for (int i = 0; i< picked.length; i++){ System.out.print(picked[i]+" "); } System.out.println(); }catch (Exception e){ e.printStackTrace(); } } } }