I am trying to have my code output the exact number of times a certain character is said in an inputted sentence (For example e).
I tried using a char and for statement so its able to count but it gives me the wrong value
int countChar;
char e = '\0';
String str;
int count = 0;
System.out.println("input your sentence:");
str = in.next();
for(i=0; i < str.length(); i++)
{ if(str.charAt(i) == e)
count++;
}
System.out.println(count);
You need to change if(str.charAt(i) == e)
to if(str.charAt(i).equals("e"))
, you don't really require a variable for this. You just require the quotation marks, and since you are comparing a string, you should use the above String.equals()
method.
If you are looking for uppercase letters as well, use the ||
(OR) operator and do the same but replace the lowercase e with an uppercase
You should use 'e' instead of '\0' when comparing the characters
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.