Java:在字符串中打印一个唯一的字符

Dex*_*tra 5 java string character unique

我正在编写一个程序,用于打印字符串中的唯一字符(通过扫描仪输入).我创建了一个尝试实现此目的的方法,但我不断获取不重复的字符,而不是字符串唯一的字符(或字符).我只想要这些独特的字母.

这是我的代码:

import java.util.Scanner;
public class Sameness{
   public static void main (String[]args){
   Scanner kb = new Scanner (System.in); 
     String word = "";

     System.out.println("Enter a word: ");
     word = kb.nextLine();

     uniqueCharacters(word); 
}

    public static void uniqueCharacters(String test){
      String temp = "";
         for (int i = 0; i < test.length(); i++){
            if (temp.indexOf(test.charAt(i)) == - 1){
               temp = temp + test.charAt(i);
         }
      }

    System.out.println(temp + " ");

   }
}            
Run Code Online (Sandbox Code Playgroud)

这里是带有上述代码的示例输出:

Enter a word: 
nreena
nrea 
Run Code Online (Sandbox Code Playgroud)

预期的产出是: ra

Boh*_*ian 10

如何应用 KISS 原则:

public static void uniqueCharacters(String test) {
    System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
Run Code Online (Sandbox Code Playgroud)


lmi*_*asf 8

根据您所需的输出,您必须替换最初在以后复制时已添加的字符,因此:

public static void uniqueCharacters(String test){
    String temp = "";
    for (int i = 0; i < test.length(); i++){
        char current = test.charAt(i);
        if (temp.indexOf(current) < 0){
            temp = temp + current;
        } else {
            temp = temp.replace(String.valueOf(current), "");
        }
    }

    System.out.println(temp + " ");

}
Run Code Online (Sandbox Code Playgroud)