我正在尝试编写一个程序来计算字符串中字母的出现次数。例如,如果用户输入“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;
}
您想要的输出:
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++;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)