I have a problem in my code, where I asked to find the number of occurrences of a character in a String, but I kept having an Exception errors and I don't know why? Here is my code:
import java.io.IOException;
import java.util.*;
import java.lang.*;
public class LabOne1 {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String strUser = scan.next().toLowerCase();
System.out.print("Enter a character: ");
char charUser = (char) System.in.read();
Character.toLowerCase(charUser);
System.out.print(charUser + "occurs " + count(strUser, charUser) +
" times in the string " + strUser);
}
public static int count(String str, char a){
int counter = 0;
for(int i = 0; i <= str.length(); i++){
if (str.charAt(i) == a){
counter++;
}
}
return counter;
}
}
Update: The issue is in the loop as the iterator should be higher than zero instead of equal or higher.
for(int i = 0; i < str.length(); i++)