0
public static int countLetter(String[] x, String y){
    int count = 0;
    for(int i = 0; i < x.length; i++){
        for(int h = 0; h < x[i].length(); h++){
            String yo = new String(x[i].substring(h,h+1));
            if(yo==y){
                count++;}
            }
        }
        return count;
    }
}

My method should return an integer that counts how many times total the letter appears in all strings of the array. (Assuming the string is one letter and I can't use charAt()).

Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27
  • 2
    `return (int)Arrays.stream(x).map(Pattern.compile(y, Pattern.LITERAL)::matcher).flatMap(Matcher::results).count();` – shmosel Oct 10 '18 at 23:51
  • `return Stream.of(x).flatMap(s -> s.chars().mapToObj(i -> (char) i)).filter(s -> s.equals(y.charAt(0))).count();` – Kartik Oct 11 '18 at 02:33
  • There is absolutely no need to `new String(..)` a substring (there was in Java 6 and earlier (maybe early Java 7 version as well), but that reason no longer exists). – Mark Rotteveel Oct 12 '18 at 15:48

3 Answers3

0

That is not how you compare strings.

Change

if(yo==y)

To

if(yo.equals(y))

Or if u want to ignore casing of letters

if(yo.equalsIgnoreCase(y))
bakero98
  • 805
  • 7
  • 18
0

The problem is on String comparison. You need to use equals() or maybe equalsIgnoreCase() when comparing 2 String in Java:

public static int countLetter(String[] x, String y) {
   int count = 0;
   for (int i = 0; i < x.length; i++) {
      for (int h = 0; h < x[i].length(); h++) {
         String yo = new String(x[i].substring(h, h + 1));
         if (yo.equals(y)) {
            count++;
         }
      }
   }
   return count;
}

You can also do this with a char instead of String:

public static int countLetter(String[] x, char y) {
   int count = 0;
   for (int i = 0; i < x.length; i++) {
      for (int h = 0; h < x[i].length(); h++) {
         if (x[i].charAt(h) == y) {
            count++;
         }
      }
   }
   return count;
}
czdepski
  • 316
  • 4
  • 9
0

You can change your code on line 6

if(yo==y)

To

if(yo.equals(y))

That should be work.

chale
  • 9
  • 1