【发布时间】:2014-03-25 21:05:17
【问题描述】:
例如,字符串“abc”应该给出 3 个唯一字符,而字符串“abcccd”应该给出 4 个唯一字符。我不允许在其中使用 Map、HashMap、TreeMap、Set、HashSet、StringBuffer 或 TreeSet。
到目前为止,我正在尝试使用 for 循环,但是当我运行程序时,我不断得到 0 个唯一字符。我是 Java 的新手,所以我真的不知道自己在做什么。
编辑:所以我改变了代码,我得到了一个结果,但它最终比我想要的少 1。我将输入“abc”,结果将显示为“2 个唯一字符”而不是 3 个。为了反驳我把 (uniqueChars + 1) 放在 println 语句中。这是一个很好的修正吗?如果用户什么都不放,它仍然会说有 1 个唯一字符。
更新代码:
userText = userText.toLowerCase(); // userText is declared earlier in the program
// as the user's input. Setting this to lowercase
// so it doesn't say "a" and "A" are two different
// characters.
int uniqueChars = 0;
for (int i = 0; i < lengthText-1; i++) { // lengthText is declared earlier
// as userText.length();
if (userText.charAt(i) != userText.charAt(i+1))
uniqueChars++;
}
System.out.println("there are " + (uniqueChars + 1) + " unique characters in your string.");
}
【问题讨论】:
-
你认为你的 for 循环会运行吗?看看你的终止条件。除此之外,您的逻辑有缺陷,您只是在比较相邻的字符。
-
循环运行,它只是给了我不正确的答案。如果我输入“abc”,程序会返回 0 个唯一字符而不是 3。我还尝试将“i
标签: java count character unique