【问题标题】:How to stop string repetition on array如何停止数组上的字符串重复
【发布时间】: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


    【解决方案1】:

    存在于 java.util 包中并扩展了 Collection 接口的 set 接口是一个无序的对象集合,其中不能存储重复值。它是一个实现数学集的接口。此接口包含从 Collection 接口继承的方法,并添加了一个限制重复元素插入的功能。有两个接口扩展集合实现,即

    for (String boys : kids) {
        Set<String> btoys = new HashSet<String>();
        btoys.add(sf.getRandomBoyToy());
        
        if (boys.endsWith("M")) {
            fw.write(boys + " (" + btoys + ")\n\n");
        }
    }
    

    【讨论】:

    • 感谢一百万穆斯塔法波亚。它对我有用! =)
    【解决方案2】:
    if (!btoys.contains(sf.getRandomBoyToy().equals(sf.getRandomBoyToy()))) {
        btoys.add(sf.getRandomBoyToy());
        x++;
    }
    

    生成 3 个玩具,首先将其中 2 个相互比较,然后检查结果布尔值是否存在于字符串列表中(可能不存在),然后附加第 3 个。
    相反,您应该生成一个,并将其用于检查和添加:

    String toy = sf.getRandomBoyToy();
    if(!btoys.contains(toy)) {
        btoys.add(toy);
        x++;
    }
    

    【讨论】:

      【解决方案3】:

      只需使用 Set 数据结构而不是 List。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-02
        相关资源
        最近更新 更多