我认为这会奏效。虽然我无法通过一个测试用例,但请随意尝试它可能对您有用。
import java.util.*;
public class OccurrenceOfChar{
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n[] = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},flag=0;
System.out.println("Enter a word:");
String input = in.nextLine();
input=input.toLowerCase();
for(int i=0;i<input.length();i++){
if(((int)input.charAt(i)-97)<0 || ((int)input.charAt(i)-97)>25){
flag=1;
}
else{
n[(int)input.charAt(i)-97]++;
}
}
if(flag==1){
System.out.println("Not a valid string");
}
else{
System.out.println("Enter the character:");
String t = in.nextLine();
String s=t.toLowerCase();
if(((int)s.charAt(0)-97)<0 || ((int)s.charAt(0)-97)>25){
System.out.println("Given character is not an alphabet");
}
else{
if(n[(int)s.charAt(0)-97]>0){
System.out.println("No of\'"+s+"\' present in the given word is "+n[(int)s.charAt(0)-97]+".");
}
else{
System.out.println("The given character \'"+s+"\' not present in the given word.");
}
}
}
}
}