【发布时间】:2021-03-13 07:13:33
【问题描述】:
我有一项大学作业,我必须阅读一个包含姓名列表的文件,并为每个人添加最多 3 个礼物。我可以做到,但礼物是重复的,而且名单中的一些人不止一次收到相同的礼物。我怎样才能阻止它,让每个人每次都能收到不同种类的礼物?
这是我的代码:
public static void main(String[] args) throws IOException {
String path = "Christmas.txt";
String line = "";
ArrayList<String> kids = new ArrayList<>();
FileWriter fw = new FileWriter("Deliveries.txt");
SantasFactory sf = new SantasFactory();
try (Scanner s = new Scanner(new FileReader("Christmas.txt"))) {
while (s.hasNext()) {
kids.add(s.nextLine());
}
}
for (String boys : kids) {
ArrayList<String> btoys = new ArrayList<>();
int x = 0;
while (x < 3) {
if (!btoys.contains(sf.getRandomBoyToy().equals(sf.getRandomBoyToy()))) {
btoys.add(sf.getRandomBoyToy());
x++;
}
}
if (boys.endsWith("M")) {
fw.write(boys + " (" + btoys + ")\n\n");
}
}
fw.close();
}
}
【问题讨论】:
标签: java arrays string random repeat