我正在尝试编写一个快速程序来计算输入字符串中的空格数。这是我目前所拥有的:
import java.util.Scanner;
public class BlankCharacters
{
public static void main(String[] args)
{
System.out.println("Hello, type a sentence. I will then count the number of times you use the SPACE bar.");
String s;
int i = 0;
int SpaceCount = 0;
Scanner keyboard = new Scanner(System.in);
s = keyboard.nextLine();
while (i != -1)
{
i = s.indexOf(" ");
s = s.replace(" ", "Z");
SpaceCount++;
}
System.out.println("There are " + SpaceCount + " spaces in your sentence.");
}
}
while 循环首先使用 s.indexOf("") 找到字符串 s 中的第一个空格,将其替换为字符 Z,然后将值 SpaceCount 加 1。重复此过程,直到 s.indexOf 找不到空格,导致 i 为 -1 并因此停止循环。
换句话说,每发现一个空格,SpaceCount 加 1,然后向用户显示空格的总数。或者应该是……
问题:SpaceCount 没有增加,而是总是打印出 2。
如果我输入“一二三四五”并打印出 String s,我会得到“oneZtwoZthreeZfourZfive”,表明有四个空格(并且 while 循环运行了四次)。尽管如此,SpaceCount 仍为 2。
程序运行良好,但它始终显示 SpaceCount 为 2,即使字符串/句子超过十个或二十个单词也是如此。即使使用 do while/for 循环,我也会得到同样的结果。我已经坚持了一段时间,我不确定为什么当 while 循环的其余部分继续执行(按预期)时 SpaceCount 停留在 2。
非常感谢任何帮助!
最佳答案
I'm just really curious on why SpaceCount doesn't change
在循环的第一次迭代中,您将 ""
替换为空(所有空格),并增加 SpaceCount
。在第二次迭代中,您什么也没找到(得到 -1
)并且什么也没替换,然后递增 SpaceCount
(得到 2
)。
我不会修改 String
,而是迭代 String
中的字符并计算空格数。
System.out.println("Hello, type a sentence. I will then count the "
+ "number of times you use the SPACE bar.");
Scanner keyboard = new Scanner(System.in);
String s = keyboard.nextLine();
int spaceCount = 0;
for (char ch : s.toCharArray()) {
if (ch == ' ') {
spaceCount++;
}
}
System.out.println("There are " + spaceCount + " spaces in your sentence.");
另外,按照惯例,变量名应该以小写字母开头。并且,您可以通过在声明变量时对其进行初始化来使代码更加简洁。
关于java - 显示输入字符串中的空格数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39803071/