有 Java 编程相关的问题?

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

java中的符号计数方法

我正在使用一个程序读取一个文本文件,然后计算数字(大写、小写、空格)。我的问题是,如何将文本的其余部分(数字,“.()/:;)一起计算

下面是一些代码

for (int b = 0; b < crunchifyLine.length(); b++) {
    if (Character.isUpperCase(crunchifyLine.charAt(b))) {
        UppeLetter++;
    }
}

for (int b = 0; b < crunchifyLine.length(); b++) {
    if (Character.isLowerCase(crunchifyLine.charAt(b))) {
        LowerLetter++;
    }
}

for (int c = 0; c < crunchifyLine.length(); c++) {
    if (Character.isWhitespace(crunchifyLine.charAt(c))) {
        spaceNum++;
    }
}       

共 (2) 个答案

  1. # 1 楼答案

    这不是一个优雅的解决方案,但它仍然适用于您:

    final int SPACE_ASCII = ' ';
        final int UPPER_CASE_LOWER_ASCII_LIMIT = 'A';
        final int UPPER_CASE_UPPER_ASCII_LIMIT = 'Z';
        final int LOWER_CASE_LOWER_ASCII_LIMIT = 'a';
        final int LOWER_CASE_UPPER_ASCII_LIMIT = 'z';
        final int DIGIT_LOWER_ASCII_LIMIT = '0';
        final int DIGIT_UPPER_ASCII_LIMIT = '9';
        final String OTHER_CHARS = "\". ' ()/ :;";
    
        int uppercaseCount = 0;
        int lowercaseCount = 0;
        int whitespaceCount = 0;
        int otherSymbolsCount = 0;
        int discardedSymbolsCount = 0;
    
        String text = "$Your String Goes here. 123#";
    
        for (int i = 0; i < text.length(); i++) {
            Character c = text.charAt(i);
            if (c == SPACE_ASCII) {
                whitespaceCount++;
            } else if ((c >= DIGIT_LOWER_ASCII_LIMIT && c <= DIGIT_UPPER_ASCII_LIMIT)
                    || OTHER_CHARS.contains(String.valueOf(c))) {
                otherSymbolsCount++;
            } else if (c >= UPPER_CASE_LOWER_ASCII_LIMIT && c <= UPPER_CASE_UPPER_ASCII_LIMIT) {
                uppercaseCount++;
            } else if (c >= LOWER_CASE_LOWER_ASCII_LIMIT && c <= LOWER_CASE_UPPER_ASCII_LIMIT) {
                lowercaseCount++;
            } else {
                discardedSymbolsCount++;
            }
        }
    
        System.out.println("White Space : " + whitespaceCount);
        System.out.println("Upper Case : " + uppercaseCount);
        System.out.println("Lower Case : " + lowercaseCount);
        System.out.println("Others : " + otherSymbolsCount);
        System.out.println("Discarded : " + discardedSymbolsCount);
    
  2. # 2 楼答案

    基于“部分代码”,我将其更改为更类似于:

    for (int b = 0; b < crunchifyLine.length(); b++) {
        if (Character.isUpperCase(crunchifyLine.charAt(b))) {
            UppeLetter++; // [sic]
        } else if (Character.isLowerCase(crunchifyLine.charAt(b))) {
            LowerLetter++;
        } else if (Character.isWhitespace(crunchifyLine.charAt(c))) {
            spaceNum++;
        } else {
            restOfTheTextTogether++;
        }
    }
    

    另一种方法是:

    restOfTheTextTogether = crunchifyLine.length() -
        UppeLetter /*[sic]*/ - LowerLetter - spaceNum;
    

    同样对于样式,您混合了以小写字母开头的变量和以大写字母开头的变量,您可以看到the automatic syntax highlighter标记通常意味着不同的东西(尽管这只是惯例)