我編寫了一個祕密的聖誕老人程序,打印出所有參與者的獨特祕密聖誕老人,並且不會在同一輸入上重複輸出。隨機數不同的輸出每次
我的問題是:
- 該計劃產生了一些重播相同的輸出...第一次運行後
- 程序掛起如果大於或等於3名的名字出現在列表中。它僅輸出少量條目的正確輸出。對於例如3個名字打印2個名字的祕密聖誕老人並掛起!
代碼如下。
SecretSanta ss=new SecretSanta();
Scanner scn=new Scanner(System.in);
do
{
System.out.println("Add the participants name:-");
String name=scn.next().trim();
ss.names.add(name);
ss.santa.add(name);
System.out.println("Do u want to add more names?");
System.out.println(" 1-YES 2-NO");
choice=scn.nextInt();
}while(choice==1);
do
{
total_size=ss.santa.size();
System.out.println(total_size);
Collections.shuffle(ss.santa);
System.out.println(ss.names.size());
System.out.println("Below is the list of participants with their secret santas");
Iterator<?> itr=ss.names.iterator();
while(itr.hasNext())
{
String name=(String)itr.next();
String SecretName;
do
{
int rand=r.nextInt(total_size);
SecretName=ss.santa.get(rand);
}while(name.equals(SecretName));
System.out.println(name+" "+SecretName);
ss.santa.remove(SecretName);
total_size=ss.santa.size();
}
ss.santa.addAll(ss.names);
Collections.shuffle(ss.santa);
System.out.println("do you want to rerun??");
System.out.println(" 1-YES 2-NO");
choice=scn.nextInt();
}while(choice==1);
我不想在每次運行時輸出不同的輸出,但只在連續運行時輸出。添加以下代碼 而(itr.hasNext()) \t \t { \t \t \t字符串名稱=(字符串)itr.next(); \t \t \t \t String SecretName; \t \t \t做 \t \t \t { \t \t \t INT蘭特= r.nextInt(TOTAL_SIZE); \t \t \t SecretName = ss.santa.get(rand); \t \t \t \t \t \t} while(name.equals(SecretName)|| s.contains(SecretName)); \t \t \t s.add(SecretName); \t \t \t System.out。println(名稱+「」+ SecretName); \t \t \t \t } \t \t \t \t \t s.removeAll(ss.names); – nnm