I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This
Your if (sentence.length() <= 0) {
is not right. Change your condition like:
System.out.println("Enter a character for which to search");
letter = in.next();
System.out.println("Enter the string to search");
sentence = in.next();
char searchLet=letter.charAt(0); // Convert String to char
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (searchLet== ch) { // Check the occurrence of desired letter.
letter++;
}
}
System.out.print(sentence.charAt(letter));