Java中的Collections.shuffle [英] Collections.shuffle in java

查看:194
本文介绍了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;
}



但是,在您提供的摘录中,rollaList之间没有连接.



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!


这篇关于Java中的Collections.shuffle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆