Im building my first program. The idea is to read a list of questions from a file and then allow the user to select a number of random questions to get asked. For instance the program will have 30 questions. However the user may only want to practice 5 questions at a time. I have reached my first real hang up.
Im writing a method that will allow the user to input how many questions they want asked. The method will output an in array of x random numbers that do not exceed the amount of questions. I then plan to use that array to call the actual questions from another method that I have already successfully built.
Here is the code for the method
public int [] ranQuest(int numQs, int totalQs) {
int [] numberQs = new int [numQs];
int maxNum = totalQs;
ArrayList<Integer> allQs = new ArrayList();
for (int x = 0; x < maxNum; x++) {
allQs.add(x);
}
Collections.shuffle(allQs);
for(int x = 0; x < numberQs.length; x++) {
numberQs[x] = allQs.get(x);
}
return numberQs;
}
I have commented out my troubleshooting print lines. Here is my test code:
public static void main(String[] args) {
GameLoad gl = new GameLoad();
Scanner scan = new Scanner(System.in);
String userAns = null;
Random randInt = new Random();
QuestGen questGen = new QuestGen();
int [] quests = questGen.ranQuest(4, 10);
for (int quest : quests) {
System.out.println(quests[quest]);
}
}
When I run the code for inputs of 3, 3 or 4, 4 it sudo works. I do not get a outofbounds exception error but the numbers are not in the order I expect. When I run the code for 3, 10 or 5, 30...I get an outofbounds exception error that dumfounds me because I think my for loop is good.
I have done a lot of searching and it seems like I may have a problem trying to convert Integers to ints, or maybe my for loop to populate the int array is not right. Is there a way or better way then the path Im on to take an array of X ints populated in order mix those up, and then populate a new smaller array?
Thanks in advance Jojo