Counting char in String
Just seeking some advice in reference to a homework problem I have for my Java 101 class. Basically it accepts a String as a parameter, and returns the number of times character 'A' is displayed. I can not seem to get the method countA down..
num = countA(length, String1, a);
public static String countA(int length, String String1,char a)
int counter = 0;
for (int i=0; i<length; i++)
if (String1 == 'a')
String1 (which should be string1) is the whole String, right? So when would it ever equal a single char? Would it even equal a single char if it was a single char? Does "a" == 'a'? Try it out.
You want to compare the char at each index of the String to 'a'. Check out the String API for useful functions.
Originally Posted by j@v@
you will return a number, why do you write, that countA is returning a String in the method declaration? ;/
if (String1 == 'a') - String1 is a string and you trying to compare it with a char? makes no sense or? (String1.charAt(i) == a). you should use a instead of 'a' or remove the parameter..
move the return count(which you should rename to counter) one line down!