I updated my code from previous suggestions, and it is only reading the first word in my sentence, any suggestions on how to get it to read the whole sentence? (I have to use a for loop)
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count ++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
Output: Enter a character for which to search h Enter the string to search hello how are you There are 1 occurrences of h in hello