由于Java没有直接从Scanner类获取char字符的方法,所以只能用String接收字符串后通过charAt()将最后一个字符赋值给char类型。然后通过deleteChar(String str)行数将String最后一个字符删除。
/*
Enter the string: Prelude In Daydream.o
Character 'o' in "Prelude In Daydream." occurs: 0 time.
Enter the string: I never want to say you unhappy.a
Character 'a' in "I never want to say you unhappy." occurs: 3 times.
*/
import java.util.Scanner;
public class CountCharOccurs {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = input.nextLine();
char ch = str.charAt(str.length() - 1);
str = deleteChar(str);
int count = count(str, ch);
System.out.println("Character '" + ch + "'" + " in \"" + str + "\"" +
" occurs: " + count + ((count > 1) ? " times." : " time."));
}
public static String deleteChar(String str) {
StringBuilder stringBuilder = new StringBuilder(str);
stringBuilder.deleteCharAt(str.length() - 1);
return stringBuilder.toString();
}
public static int count(String str, char a) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (a == str.charAt(i))
count++;
}
return count;
}
}