有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java显示输入字符串中的空格数?

我正在尝试编写一个快速程序,计算输入字符串中的空格数。这就是我目前的情况:

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

如果我输入“一二三四五”并打印出字符串s,我会得到“oneztwozthrezfourzfive”,表示有四个空格(while循环运行四次)。尽管如此,SpaceCount仍然保持在2

程序运行正常,但它始终显示2的空格计数,即使字符串/句子超过10或20个单词。即使使用do while/for循环,我也会得到同样的结果。我已经在这个问题上纠结了一段时间,不知道为什么当while循环的其余部分继续执行(如预期的那样)时,SpaceCount会被困在2

非常感谢您的帮助


共 (3) 个答案

  1. # 1 楼答案

    你在计算空白方面走了很长的路。替换此代码块:

        while (i != -1)
        {
            i = s.indexOf(" ");
            s = s.replace(" ", "Z");
            SpaceCount++;
        }
    

    有了这个:

    char[] chars = s.toCharArray();
    for(char c : chars){
        if(c == ' '){
            spaceCount++;
        }
    }
    

    这更优雅,而且(我相信)执行起来也更便宜。希望这对你有用

  2. # 2 楼答案

    使用这个,简单明了。将空格字符替换为none,并用字符串的实际长度减去它。这应该给出字符串中的空格数

    Scanner n = new Scanner(System.in);
    n.useDelimiter("\\n");
    String s = n.next();
    int spaceCount = s.length() - s.replaceAll(" ", "").length();
    System.out.println(spaceCount);
    
  3. # 3 楼答案

    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.");
    

    此外,按照惯例,变量名应该以小写字母开头。而且,通过在声明变量时初始化变量,可以使代码更加简洁