0

I am stuck on a problem in having my counter increment. I'm not sure what I am doing wrong though. Sorry if this is a beginner mistake, but I have not found a solution where I understand or helps yet.

  public static int duplicates(String[] text, int numWords){
            int currentCount = 1;
            for (int i=0; i<numWords-1; i++){
                for (int j=i+1; j<numWords; j++){
                    if (text[i] == text[j]){
                        currentCount++;

                    }
                }   
            }

            return currentCount;
        }

4 Answers4

1

To compare objects in java use .equals() method instead of "==" operator

if (text[i] == text[j]) need to change to if (text[i].equals(text[j]))

if you want to ignore the case use .equalsIgnoreCase() instead of .equals()

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0
if (text[i] == text[j])

Your mistake is in the line above.

In Java you should not use the == operator to compare Strings. That will check if the 2 strings are the same object (identity comparison), but you want to check whether they have the same content (value comparison).

You need to use text[i].equals(text[j]) instead.

If your method is supposed to handle null values in the array (i.e. text[i] can be null) then you will need to check for null before you call equals.

Tim
  • 6,406
  • 22
  • 34
0

replace if (text[i] == text[j]){ to if (text[i].equals(text[j])){

use this way

public static int duplicates(String[] text, int numWords){
            int currentCount = 1;
            for (int i=0; i<numWords-1; i++){
                for (int j=i+1; j<numWords; j++){
                    if (text[i].equals(text[j])){
                        currentCount++;

                    }
                }   
            }

            return currentCount;
        }
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

When you are comparing string values, use the equals method.

if (text[i].equals(text[j])) {
josh
  • 365
  • 3
  • 12