Reputation: 1
"This is my code"
public static void main(String[] args) {
int letter_count = 0;
String check_word = new String ("How to equals a single character in string and then calculate it ");
String single_letter = " ";
int i = 0;
for ( i = 0; i < check_word.length(); i++ ) {
single_letter = check_word.substring(0);
if (single_letter.equals("a") ); {
letter_count ++;
}
}
System.out.println ( " - \"a\"" + " was found " + letter_count + " times");
}
Upvotes: 0
Views: 148
Reputation: 124215
One of your problems is that there is ;
after your if (single_letter.equals("a") )
condition so your code
if (single_letter.equals("a") ); {
letter_count ++;
}
effectively is the same as
if (single_letter.equals("a") ){
//empty block "executed" conditionally
}
//block executed regardless of result in `if` condition
{
letter_count ++;
}
Other problem is that
single_letter = check_word.substring(0);
will get substring of check_word
from index 0
which means that it will store same string as check_word
. Consider using charAt
method with i
instead of 0
. This will return simple char
so you will need to compare it with ==
like check_word.charAt(i)=='a'
.
Other (and probably better) approach would be just iterating over all characters of string with
for (char ch : check_word.toCharArray()){
//test value of ch
}
Upvotes: 2
Reputation: 2798
Why don't you use a character, like this:
public static void main(String[] args) {
int letter_count = 0;
String check_word = new String ("How to equals a single character in string and then calculate it ");
char toCheck = 'a';
for (int i = 0; i < check_word.length(); i++) {
char cursor = check_word.charAt(i);
if (cursor == toCheck) {
letter_count++;
}
}
System.out.println ( " - \"a\"" + " was found " + letter_count + " times");
}
Upvotes: 0
Reputation: 553
try...
public static void main(String[] args) {
int letter_count = 0;
char[] check_word = "How to equals a single character in string and then calculate it "
.toCharArray();
char single_letter = 'a';
for (int i = 0; i < check_word.length; i++) {
if (single_letter == check_word[i]) {
letter_count++;
}
}
System.out.println(" - \"a\"" + " was found " + letter_count + " times");
}
Upvotes: 0
Reputation: 38345
You seem to be confused about what the substring function does. This line:
single_letter = check_word.substring(0);
essentially returns the whole of check_word
and stores it inside of single_letter
. I suspect what you actually wanted was this:
single_letter = check_word.substring(i, i + 1);
to get the single letter at that position.
You could also change it to:
if(check_word.charAt(i) == 'a') {
letter_count++;
}
Upvotes: 4