1

我正在尝试从输入中删除重复项。有很多方法可以做到这一点,使用 ArrayList、LinkedList、Hash set 等。我知道如何做到这一点,如果输入指定为 say{“apple”、“ball”、“apple”、“cat”}在问题中。但我想使用扫描仪类并获取输入说一行并希望删除字符中的重复项,或删除重复的单词。你有一个简单的方法来做到这一点。我已经为之前的场景包含了我的工作代码。

public static void main(String[] args) {
        // TODO code application logic here

        Scanner scan= new Scanner(System.in);
        String[] str= {"a", "b", "c", "a"};
        System.out.println("enter text");
        List<String> l= 
                Arrays.asList(str);
        System.out.println(l);
        Set<String> set= new HashSet<String>(l);
        System.out.println(set);
    }
4

1 回答 1

1

The following will read each word and add it to the hashset (which removes dups automatically which you figured out) and will stop when a word is ! and print out the set..

    Scanner scan= new Scanner(System.in);
    HashSet<String> set = new HashSet<String>();
    String s;
    while (!(s = scan.next()).equals("!")) {
        set.add(s);
    }
    System.out.println(set);
于 2013-02-19T00:04:36.280 回答