private static void CountLetters(Scanner sc) {
System.out.println("Enter a string");
String s = sc.nextLine();
System.out.println("Enter a letter");
char c = sc.nextLine().charAt(0);
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c)
res++;
System.out.println(res + " " + c + " i " + s);
}
输出重复其自身的次数与字母相同。知道为什么以及如何解决它吗? 当前输出示例:
输入字符串
你好世界 输入字母
l
在Hello世界中为0 l
在Hello世界中为0 l
Hello world中有1公升
Hello world中2 l
Hello world中2 l
Hello world中2 l
Hello world中2 l
Hello world中2 l
Hello world中2 l
Hello world中3 l
Hello world中3 l
答案 0 :(得分:1)
如果您不跟踪代码,则不应将输出语句放入循环中:
int res = 0;
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == c)
res++;
}
System.out.print(res + " " + c + " in" + s);
答案 1 :(得分:0)
因为您的打印语句存在于循环中,所以它将在每次执行循环时打印当前计数,这将为您提供多行/计数。将打印移到循环外将确保仅在解析整个字符串后才执行一次:
private static void CountLetters(Scanner sc) {
System.out.println("Enter a string");
String s = sc.nextLine();
System.out.println("Enter a letter");
char c = sc.nextLine().charAt(0);
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c)
res++;
}
// Moved print statement outside of the loop; changed "i" to "in".
System.out.println(res + " " + c + " in" + s);
}