我正在编写一个程序,它将打印字符串中的唯一字符(通过扫描器输入)。我创建了一个方法来尝试完成这个任务,但我一直得到不是重复字符的字符,而不是字符串中唯一的字符(或字符)。我只想要独特的字母。
这是我的代码:
预期输出应为:
这是我的代码:
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 + " ");
}
}
以下是使用上述代码的示例输出:
Enter a word:
nreena
nrea
预期输出应为:
ra
e
是一个重复的字符,你仍然在输出中得到了它。你期望的输出是ra
吗? - RaminSchar[] array = test.toCharArray();
然后循环遍历array
中的每个字母,如果没有匹配项,则执行temp = temp + test.charAt(i);
。 - RaminS