计算java中的符号

时间:2016-05-23 22:52:36

标签: java methods symbols

我正在使用一个程序读取一个文本文件,然后计算(upperCase,lowerCase,space)的数量。我的问题是我如何计算其余的文本,如(数字,&#34) ;。'()/:;)在一起?

这里有一些代码

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 个答案:

答案 0 :(得分: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标记通常意味着不同的东西(即使这只是惯例)。

答案 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);