Java中的Collections.shuffle
问题描述:
我这里有一个示例程序,该程序使用Collections并对数组进行混洗以避免重复显示问题.但是它不起作用,仍然有问题重复.这里是代码,请帮助我检测我的程序中有什么错误.
//collections.shuffle的代码
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
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);
}
}
}
答
这是将数组iof换为零的方法:
This is shuffling an array iof zeros:
Collections.shuffle(Arrays.asList(roll));
您是否真的要将数组aList
设置为相同值50次?
这很多很好地打乱了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;
}
但是,在您提供的摘录中,roll
和aList
之间没有连接.
However there is no connection between roll
and aList
in the snipet you provided.
我只想设置问题,w/c的值为50,没有重复的问题或重复项.当您跟踪我的代码时,您是否发现了问题所在?请立即帮助我.谢谢!
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!