Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 ero

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading