I am trying to figure out why this one part of my program is not working. I am trying to count the number of the letter s a user types in when prompted using indexOf. For some reason it will not work correctly. Thanks for any help.

    import java.util.Scanner;

public class MyStringMethods {

    private String myStr="";

    public void readString()
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Please enter a string: ");
        String myStr = keyboard.nextLine();

    public void setString(String s)
        myStr = s;
    public int countOccurrences(String s)  // This is the line that will not work with my code.
        int length = myStr.length();
        int countS = 0;
        int index = 0;

        while (index < length) 
            if (myStr.indexOf(s , 0) == 's' ) 
                countS = countS + 1;
            index = index + 1;


Recommended Answers

All 4 Replies

can you specify the 'not working' part a bit more?
what is 'not working' ? does it compile? do you get compile time errors? does it run? are run time exceptions thrown? do you get a stacktrace?
do you get an unexpected result?

Here is what you want to do if you want to get the number of occurance

for(int i; i<length<i++)
someLetter = position of the letter at i
check if someLetter equals the letter you are checking for
if it equals, increse index by

indexOf will return the first occurance of "s" in your code, but won't return the total number of occurance

Thank you for your help!

@Slavi, you need to point out what is wrong and give a guide, not simply give away the answer...

@OP, look at your code portion...

 while (index < length) {
  if (myStr.indexOf(s , 0) == 's' ) {
    countS = countS + 1;
  index = index + 1;

Now tell me what this code portion is doing? And what indexOf(int, int) is supposed to look for? I can tell you that your number count is equal to your string length, isn't it? How could I know that? If you can explain what you are doing in the code portion, you should find out why your code is wrong.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.