Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have here a sample program that use Collections and shuffle the array to avoid the repetition of questions to display.But it doesn't work,there still a duplication of questions.Here is the code,please help me to detect what is the error in my program.

//Code for collections.shuffle
Java
String cntq = request.getParameter("quest");
int totq = Integer.parseInt(cntq);
ArrayList<imgaddquestBEAN> aList = new ArrayList<imgaddquestBEAN>();
projectDAO pDAO1 = new projectDAO();
	
Random diceRoller = new Random();//Random number generator
			int i=0;
			int[] roll = new int[totq];
			int s = 50;
			try{
				//--- Initialize the array to the ints 0-49
				Collections.shuffle(Arrays.asList(roll));
				for (i=0; i< roll.length; i++) {
		    		roll[i] = i;
					roll[i] = diceRoller.nextInt(s);
					aList = pDAO1.displayquest(true, s);
					request.setAttribute("one", aList);
				}
				//--- Shuffle by exchanging each element randomly
				for (i=0; i< roll.length; i++) {
		    		int randomPosition = diceRoller.nextInt(roll.length);
		    		int temp = roll[i];
		    		roll[i] = roll[randomPosition];
		    		roll[randomPosition] = temp;
					}
			}catch(SQLException ex){
				ex.printStackTrace();
			}
			request.setAttribute("one", aList);
			ServletContext sc = this.getServletContext();
			RequestDispatcher rd = sc.getRequestDispatcher("/test1.jsp");
			rd.forward(request, response);
		}
	}

}
Posted
Updated 23-Feb-10 22:56pm
v2

This is shuffling an array iof zeros:
Collections.shuffle(Arrays.asList(roll));


Do you really want to be setting the array aList 50 times to the same value?

This lot shuffles the order of roll nicely:
for (i=0;
        i > roll.length;
        i++)
{
    int randomPosition = diceRoller.nextInt(roll.length);
    int temp = roll[i];
    roll[i] = roll[randomPosition];
    roll[randomPosition] = temp;
}


However there is no connection between roll and aList in the snipet you provided.
 
Share this answer
 
I just want to set the questions w/c has the value of 50 with no repetition of questions or duplicates. As you traced on my codes, did you detect what is the problem? Please help me immediately.Thanks!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900