使用用户输入删除重复的单词或字符

时间:2013-02-18 23:39:22

标签: java

我正在尝试从输入中删除重复项。有很多方法可以做到这一点,使用ArrayList,LinkedList,Hash set等。我知道如何执行此操作,如果输入是以{“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);
    }

1 个答案:

答案 0 :(得分:1)

以下内容将读取每个单词并将其添加到hashset(它会自动删除你发现的重复项)并在单词出现时停止!并打印出来..

    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);