Java 该方法应该计算a‘;的次数’‘’;,或者‘”;出现在文本中

Java 该方法应该计算a‘;的次数’‘’;,或者‘”;出现在文本中,java,Java,到目前为止,这就是我所拥有的,我不知道从这里可以走到哪里。 (我是初学者,请尝试使用简单的逻辑让我理解) 公共静态无效语句(字符串文本){ 字符串逗号=“,”; 字符串句点=“.”; 字符串问题=“?”; 字符串ex=“!”; text=“…,?”; int c=0; 对于(int i=0;i

到目前为止,这就是我所拥有的,我不知道从这里可以走到哪里。 (我是初学者,请尝试使用简单的逻辑让我理解)

公共静态无效语句(字符串文本){
字符串逗号=“,”;
字符串句点=“.”;
字符串问题=“?”;
字符串ex=“!”;
text=“…,?”;
int c=0;
对于(int i=0;i
这里有一些多余的代码行。完全删除else块应该可以做到这一点:

public static void countSentences(String text) {
    char comma = ',';
    char period = '.';
    char Question = '?';
    char ex = '!';
    text = "..,,??!!";
    int c = 0;

    for (int i = 0; i < text.length(); i++) {
        if (comma == text.charAt(i) || period == text.charAt(i) || 
            Question == text.charAt(i) || ex == text.charAt(i)) {
            c += 1;
        }
    }
}
公共静态无效语句(字符串文本){
字符逗号=',';
字符周期=';
字符问题='?';
char ex='!';
text=“…,?”;
int c=0;
对于(int i=0;i
这有点像扰流板,但您可以使用替换方法:

public static int countSentences(String text) {
    return text.length() - text.replaceAll("[.?!]", "").length();
}

这只是将原始文本的长度与所有
的文本长度进行比较已删除。

您也可以使用流

public static void countSentences(String text) {
    char comma = ',';
    char period = '.';
    char Question = '?';
    char ex = '!';
    String text = "..,,??!!";
    long count = text.chars().filter(ch -> ch == comma ||ch == Question ||ch == period ).count();
}

由于使用的是for循环,所以不需要行“i++;”,i会自动递增
“,”。equals(“,”)
将返回
false
。即使是相同的文本,字符串也不等于字符。您需要更改返回类型
public static void countSentences(String text) {
    char comma = ',';
    char period = '.';
    char Question = '?';
    char ex = '!';
    String text = "..,,??!!";
    long count = text.chars().filter(ch -> ch == comma ||ch == Question ||ch == period ).count();
}