【发布时间】:2016-10-02 08:07:59
【问题描述】:
我正在尝试编写一个快速程序来计算输入字符串中空格的数量。这是我目前所拥有的:
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 中的第一个空格,将其替换为 char 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。
非常感谢任何帮助!
【问题讨论】:
-
如果你的字符串没有尾随空格我的意思是在字符串之前和之后,那么你也可以使用
StringTokenizer tokenizer = new StringTokenizer(str, " "); System.out.println("total number of spaces are : " + (tokenizer.countTokens() - 1));如果你在计算空格之前修剪字符串 -
我会尝试其他人提到的方法。我真的很好奇为什么 SpaceCount 不会改变。谢谢。
标签: java