我正在尝试编写一个快速程序,该程序计算输入的字符串中的空格数。这是我到目前为止的内容:

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,然后将1加到值SpaceCount上。重复此过程,直到s.indexOf找不到空格,导致i为-1,从而停止循环。

换句话说,每找到一个空白,SpaceCount就会增加1,然后向用户显示空白的总数。或者应该是...

问题:SpaceCount不会增加,而是总是打印出2。

如果我键入“一二三四五”并打印出String,我将得到“ oneZtwoZthreeZfourZfive”,表明有四个空格(而while循环运行四次)。尽管如此,SpaceCount仍为2。

该程序运行良好,但是即使字符串/句子超过十个或二十个单词,它也始终显示SpaceCount为2。即使使用do while / for循环,我也会得到相同的结果。我已经在这里停留了一段时间,并且不确定在while循环的其余部分继续执行时,为什么SpaceCount停留在2。

任何帮助深表感谢!

最佳答案

我只是很好奇为什么SpaceCount不会改变


在循环的第一次迭代中,将" "替换为空(所有空格),并递增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/

10-09 13:19