我正在尝试编写一个计算字符串中字母出现次数的程序。例如,如果用户输入“Java”,它将显示“j:1 a:2 v:1”。但是,我的程序似乎有问题,当我输入单词java时,这就是它显示的“j:0 a:1 v:0”
Scanner myScanner = new Scanner(System.in);
String s = myScanner.nextLine();
int i = 0;
int j = 0;
int cnt = 0;
int length = s.length();
char ch;
for (i = 0; i < length; i++) {
ch = s.charAt(i);
if (s.indexOf(ch) < i)
continue;
for (j = (i + 1); j < length; j++) {
if (s.charAt(j) == ch)
cnt++;
}
System.out.println(ch + ": " + cnt);
cnt = 0;
}
答案 0 :(得分:2)
你的第二个for-loop没有搜索每个字母的整个单词。
例如,在搜索j
时,它仅查看ava
,因为它始于i + 1
(0 + 1) = 1
a
字符串java
中的j
0
将是for (j = (i + 1)..)
的索引。改变
(j = 0..)
到
{{1}}
答案 1 :(得分:2)
您想要的输出:
Enter your String: Mascarena
M: 1
a: 3
s: 1
c: 1
r: 1
e: 1
n: 1
代码出错:
for (j = (i + 1); j < length; j++) { //It is omitting the first letter and searches the remaining
if (s.charAt(j) == ch)
cnt++;
}
修正:
for (j = 0; j < length; j++) { //For a specific letter searches the whole string.
if (s.charAt(j) == ch)
cnt++;
}
答案 2 :(得分:1)
public static String numberOfOccurence(String data) {
String result = "";
while (!data.isEmpty()) {
result += String.valueOf(data.charAt(0))+ StringUtils.countOccurrencesOf(data, String.valueOf(data.charAt(0)));
data = data.replaceAll(String.valueOf(data.charAt(0)), "");
}
return result;
}
输入:aabacbd
输出:a3b2c1d1