rayray
rayray

Reputation: 21

How do I count the number of occurrences of a character in a string?

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0); //getting the character by itself
        int counter=0;
        for(int index= 0; index < theString.length(); index++)
        {
            char ch = userInput.charAt(index);
            if (ch==i) //comparing the chosen character to each character in the string
                counter++; //keeping track of how many times you find a match

I am brand new to programming and I have to write a program that will count the number of occurrences of a character chosen by the user in a string that is also an input. This is just the part of the program that has the problem, the error I get when running is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1. Not sure what I'm doing wrong!

Upvotes: 1

Views: 241

Answers (4)

Eddie Martinez
Eddie Martinez

Reputation: 13910

Change To:

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0);//getting the character by itself
        int counter=0;
        for(int index= 0; index< userInput.length(); index++)
        {
            char ch = userInput.charAt(index);
            if (ch==i)//comparing the chosen character to each character in the string
                counter++;//keeping track of how many times you find a match

you get the out of range because you are not iterating over the user input.

Upvotes: 1

sumanta
sumanta

Reputation: 359

Check the line number in the stack trace and then debug.

Upvotes: -1

brso05
brso05

Reputation: 13232

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0);//getting the character by itself
        int counter=0;
        for(int index= 0; index< theString.length(); index++)
        {
            char ch = **theString**.charAt(index);
            if (ch==i)//comparing the chosen character to each character in the string
                counter++;//keeping track of how many times you find a match

My assumption is that you want to loop through theString comparing each letter of that to the original char. Remove the ** from theString I just added it to draw your attention to the change. I'm guessing theString is defined elsewhere in your code.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198461

    for(int index= 0; index< theString.length(); index++)

Where does theString come from? I suspect you mean userInput.

Upvotes: 1

Related Questions