Reputation: 21
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
Reputation: 13910
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
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
Reputation: 198461
for(int index= 0; index< theString.length(); index++)
Where does theString
come from? I suspect you mean userInput
.
Upvotes: 1