【发布时间】:2016-01-28 02:46:50
【问题描述】:
我让我的代码以预期的方式工作,但是当我尝试制作多个排列列表时,它给了我第一个并且不会改变它。 我需要使用 Arraylist 制作一个从 1 到 10 的排列列表,并捕获代码中可能发生的一个错误。然后我们必须复制该代码,以便获得 9 行不同的排列。
import java.util.ArrayList;
import java.util.Random;
public class Permutations
{
ArrayList <Integer> Perm = new ArrayList <Integer> ();
ArrayList <Integer> Print = new ArrayList <Integer> ();
int counter = 9;
int List = 1;
public void ArrayList()
{
Perm.add(1);
Perm.add(2);
Perm.add(3);
Perm.add(4);
Perm.add(5);
Perm.add(6);
Perm.add(7);
Perm.add(8);
Perm.add(9);
Perm.add(10);
}
public void PermutationGenerator()
{
ArrayList();
Random rand = new Random();
int value = rand.nextInt(10) + 1;
while(Print.size() < 10)
{
try
{
while(Print.contains(value))
{
value = rand.nextInt(10) + 1;
}
Print.add(value);
Perm.remove(value);
}
catch(IndexOutOfBoundsException a)
{
System.out.println("");
}
}
System.out.println("List" + List + ":" + Print.toString());
List++;
if(List < 10)
{
PermutationGenerator();
}
}
这是打印出来的:
List1:[9,6,5,4,10,2,8,7,1,3]
List2:[9,6,5,4,10,2,8,7,1,3]
List3:[9,6,5,4,10,2,8,7,1,3]
List4:[9,6,5,4,10,2,8,7,1,3]
List5:[9,6,5,4,10,2,8,7,1,3]
List6:[9,6,5,4,10,2,8,7,1,3]
List7:[9,6,5,4,10,2,8,7,1,3]
List8:[9,6,5,4,10,2,8,7,1,3]
List9:[9,6,5,4,10,2,8,7,1,3]
【问题讨论】:
-
我认为一旦您的打印大小为 10,它就不再执行 while 循环并一遍又一遍地打印出相同的循环
-
所以我需要将所有值重置为原始值才能正常工作
-
为什么你认为它应该打印不同的值?你能描述一下是哪部分造成的吗?
-
代码运行一次并获得第一行,然后我在底部的一个while循环中继续运行生成器,因此由于随机函数而产生了另一条不同的行。