0

Say I have two strings:

String s1 = "My name is Alex."

String s2 = "My name is Nick."

I want the program to count mutual words and return the value. With those strings, the returned value would be 3, because of the 3 words both have in common: my, name, is. For some reason, in my program, the num value returned is always 0.

public static int sameWord(String s1, String s2) {

    int num = 0;
    String[] a = s1.split(" ");
    String[] b = s2.split(" ");

    for (int i = 0; i < a.length; i++) { 
        for (int j = 0; j < b.length; j++) {
            if (a[i] == b[j]) {
                num++;
            } 
        }
    }

    return num; 
}
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Vartan
  • 15
  • 1
  • 3
  • 2
    You're using == to compare strings -- you should be using `.equals` – jackarms Nov 17 '16 at 04:15
  • 1
    The way I would do this, in Java 8+, is something like `return (int) Stream.of(a).filter(x -> Stream.of(b).anyMatch(y -> x.equals(y))).count();` - or return a `long` and remove the cast. I would also prefer `\\s+` as a regex (over `" "`). Finally, don't use `==` to compare `Object` values. – Elliott Frisch Nov 17 '16 at 04:23

1 Answers1

-1

As jackarms said, you are using == to compare strings where you should be using .equals. See this.

Try

  int num = 0;
  String[] a = s1.split(" ");
  String[] b = s2.split(" ");

  for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < b.length; j++) {
          if (a[i].equals(b[j])) {
              num++;
          }
      }
  }

  return num;
Community
  • 1
  • 1