gpt4 book ai didi

java - 计数字符方法异常错误?

转载 作者:行者123 更新时间:2023-12-02 07:03:23 25 4
gpt4 key购买 nike

我从这个网站上的一个很好的答案中复制了这段代码(计算字符串中的字符并返回计数),并稍微修改了它以满足我自己的需要。但是,我的方法似乎遇到了异常错误。

如果有任何帮助,我将不胜感激。

请原谅我的代码中的任何错误,因为我仍在学习 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;

}

}

}

这是一个异常(exception):

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method count(String) in the type CountTheChars is not applicable for the arguments (int)

at CountTheChars.main(CountTheChars.java:12)

最佳答案

您的方法 public static int count(String s, int countR) 中缺少 return 语句。目前,如果 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;

}

}

关于java - 计数字符方法异常错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16376389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com