Return the number of times a character shows up in a string

Ben Berinsky
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 + "?");
    }
}

There is an error with this code and I am not sure how to fix it. This code is supposed to return the number of times a letter shows up in a message that the user inputs. I have struggled to figure out what I need to change without error.

Elliott Frisch

The first mistake is in findLetter where you have

count = count++; // this is effectively count = count;

That should be

count++; // or count = count + 1;

Then you aren't calling findLetter. Change your current println to something like

System.out.printf("%s contains %s %d times.%n", message, letter, 
        test.findLetter(letter, message));

With no other changes, I then get

Apples and Oranges contains p 2 times.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324290998&siteId=291194637