有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在使用HashMap时给出条件

问题:

编写一个程序来打印给定句子中的所有唯一字符。 如果未找到唯一字符,请打印“无唯一字符”。 如果发现了唯一字符,请按示例输出中所示打印这些字符

我的代码:

public class Unique {
    public static void main(String[] args) {
        LinkedHashMap<Character, Integer> list = new LinkedHashMap<Character, Integer>();
        System.out.println("Enter the sentence: ");
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        if(!Pattern.matches(".*[a-zA-z]+.*[a-zA-z]",s)) {
            System.out.println("Invalid Sentence");
        } else {
            for(Character c : s.toCharArray()) {
                if (list.containsKey(c)) {
                    list.put(c, list.get(c) + 1);
                } else {
                    list.put(c, 1);
                }
            }
            System.out.println("Unique characters:");
            for(Map.Entry<Character, Integer> e: list.entrySet()) {
                if((int)e.getValue() == 1)   
                   System.out.println(e.getKey());
            }
        }
    }
}

我不知道当找不到唯一字符时,如何给出“没有唯一字符”的条件


共 (0) 个答案