Java 计数字符方法异常错误?

Java 计数字符方法异常错误?,java,Java,我从这个网站上的一个好答案中复制了这段代码(计算字符串中的字符并返回计数),并对其进行了轻微的修改以满足我自己的需要。 然而,我的方法中似乎出现了异常错误 我将非常感谢您的帮助 请原谅我代码中的任何错误,因为我还在学习Java 这是我的密码: public class CountTheChars { public static void main(String[] args){ String s = "Brother drinks brandy."; int countR

我从这个网站上的一个好答案中复制了这段代码(计算字符串中的字符并返回计数),并对其进行了轻微的修改以满足我自己的需要。 然而,我的方法中似乎出现了异常错误

我将非常感谢您的帮助

请原谅我代码中的任何错误,因为我还在学习Java

这是我的密码:

public class CountTheChars {

public static void main(String[] args){

    String s = "Brother drinks brandy.";

    int countR = 0;

    System.out.println(count(s, countR));

}


public static int count(String s, int countR){

    char r = 0;

    for(int i = 0; i<s.length(); i++){

        if(s.charAt(i) == r){

            countR++;

        }

        return countR;

    }

}

}

方法
公共静态int count(字符串s,int countR)
中缺少返回语句。当前,如果
s.length()==0,则不会返回
int

这应该如预期的那样起作用:

public class CountTheChars {

    public static void main(String[] args) {

        String s = "Brother drinks brandy.";

        int countR = 0;

        System.out.println(count(s, countR));

    }

    public static int count(String s, int countR) {

        for (int i = 0; i < s.length(); i++) {

            if (s.charAt(i) == 'r') {

                countR++;

            }

        }

        return countR;

    }

}
公共类CountTheChars{
公共静态void main(字符串[]args){
String s=“兄弟喝白兰地。”;
int countR=0;
System.out.println(count(s,countR));
}
公共静态整数计数(字符串s,整数计数r){
对于(int i=0;i
为什么不能使用
s.length()
来计算
字符串s
中的字符数(即字符串长度)

编辑:更改为包含“计数字符r的发生次数”。将函数调用为
count(s,countR,r)
并在
main

public static int count(String s, int countR, char r){

    countR= 0;
    for(int i = 0; i<s.length(); i++){

        if(s.charAt(i) == r){

            countR++;

        }

        return countR;

    }

}
公共静态整数计数(字符串s、整数计数r、字符r){
countR=0;
对于(int i=0;i2个问题:

  • 进行s.charAt比较时的计数方法(i)将单词s中的每个字母与一个名为r的变量进行比较,该变量被设置为0。这意味着,从技术上讲,你的方法是计算数字0在句子中出现的次数。这就是为什么你得到0。要解决这个问题,请删除r变量,在比较中,使用s.charAt(i)=='r'作为比较。注意r周围的撇号表示您特别指的是字符r

  • 对于字符串为nothing的情况,count方法没有正确返回,这意味着它的长度为零,这意味着您的for循环没有运行,并且您的方法将跳过它以及其中的return语句。若要解决此问题,请将return语句移到方法的最底部,这样无论返回的是什么如果您输入一个字符串,return语句将始终返回(因为您的方法希望返回int,所以应该返回)


  • 例外情况是什么?我猜你还没有重新编译你的Eclipse项目。这么做。这到底是什么意思?我以前从未见过它?啊,会的…啊,明白了。我的返回位置错误。很好,谢谢你=]事实上,我已经修改了返回计数的位置,并且删除了错误,但是它返回了0?这就是因为你的条件<代码>如果(s.charAt(i)=r)
    永远都不是真的。我现在明白了。谢谢你的帮助。它现在运行良好。目标似乎是计算特定字符的出现次数(看起来像是“r”的数量)在字符串中,而不是字符串的总长度。这是正确的。计算字符串s中使用字符“r”的次数。更新了代码以执行此操作。您已帮助解决了我的问题。它可以正常工作,谢谢。无需担心。如果您可以对此答案进行投票并选择它作为答案,那就太好了:)
    public static int count(String s, int countR, char r){
    
        countR= 0;
        for(int i = 0; i<s.length(); i++){
    
            if(s.charAt(i) == r){
    
                countR++;
    
            }
    
            return countR;
    
        }
    
    }