[英]Need to find the character most frequent in a string and return the number of times it appears
[英]Return the number of times a character shows up in a string
public class StringFind {
/** findLetter looks for a letter in a String
* @param String letter to look for
* @param String text to look in
* @return boolean true if letter is in text
* After running the code, change this method to return
* an int count of how many times letter is in the text.
*/
public int findLetter(String letter, String text) {
int count = 0;
for(int i=0; i < text.length(); i++) {
if (text.substring(i, i+1).equalsIgnoreCase(letter)) {
count = count++;
}
}
return(count);
}
public static void main(String args[]) {
StringFind test = new StringFind();
String message = "Apples and Oranges";
String letter = "p";
System.out.println("Does " + message + " contain a " + letter + "?");
}
}
此代码有错误,我不确定如何修复它。 此代码应该返回字母在用户输入的消息中出现的次数。 我一直在努力弄清楚我需要毫无错误地改变什么。
第一个错误是在你有的findLetter
中
count = count++; // this is effectively count = count;
那应该是
count++; // or count = count + 1;
那你就不会打电话给findLetter
。 将您当前的println
更改为类似
System.out.printf("%s contains %s %d times.%n", message, letter,
test.findLetter(letter, message));
没有其他变化,然后我得到
Apples and Oranges contains p 2 times.
要完成 Elliott Frisch 给出的答案,您的 function 的第一个参数错误,它是一个字符而不是字符串,鉴于此,您需要使用 function charAt 来更改在字符串中查找字符的方式,使其成为更简单( https://www.w3schools.com/java/ref_string_charat.asp )。 这不是强制性的改变,但我认为它更有意义。
public class StringFind {
/** findLetter looks for a letter in a String
* @param String letter to look for
* @param String text to look in
* @return boolean true if letter is in text
* After running the code, change this method to return
* an int count of how many times letter is in the text.
*/
public int findLetter(char letter, String text)
{
int count = 0;
for(int i=0; i < text.length(); i++)
{ if(text.charAt(i) == letter)
count++;
}
return(count);
}
public static void main(String args[])
{
StringFind test = new StringFind();
String message = "Apples and Oranges";
Character letter = 'p';
System.out.printf("%s contains %s %d times.%n", message, letter, test.findLetter(letter, message));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.