我正在尝试创建一个方法,通过打印句子和指定的字符及其计数来计算指定字符在给定字符串中出现的次数。
这是我到目前为止所完成的事情: -
import java.util.Scanner;
public class Program4 {
public int count ( String sentence, char letter)
{
int times = 0;
for (int x=0;x<sentence.length();x++)
{
if (sentence.charAt(x) ==letter){times++;}
}
return times;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
}
program4.count("Hello World",'o');
scan.close();
}
}
我知道我需要一个&#34; system.output.println&#34;但我不知道里面有什么价值来获得我想要的输出。我很感激任何帮助,我是java的初学者。谢谢。
答案 0 :(得分:0)
它有效,你在代码中有编译时错误
import java.util.Scanner;
public class Program4 {
public int count(String sentence, char letter) {
int times = 0;
for (int x = 0; x < sentence.length(); x++) {
if (sentence.charAt(x) == letter) {
times++;
}
}
return times;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
int timesCount = program4.count("Hello World", 'o');
System.out.println("count is :" + timesCount);
scan.close();
}
}