0

I'm making a little program that looks for keywords in sentences to decided the sentiment. I know it's already been done and much better I am just trying to make something over winter break to keep what I learned this semester stay in my head.

I wrote this method to take in a file that was turned into an ArrayList and the user's input which was also turned into an ArrayList, and compare then one by one looking for keywords. These keywords are stored in the fileList.

No matter what I do this method always returns 0 and the if statement never returns true. When I make this outside of the method and add each element using the .add() and then compare, it works but this way I have currently it doesnt.

public static  int compareInput(ArrayList<String> fileList, ArrayList<String> userInput) {
    int counter = 0;
    for(int i = 0; i < userInput.size(); i++) {
        for(int j = 0; j < fileList.size(); j++) {
            if(userInput.get(i) == fileList.get(j)) {
                counter = counter + 1;
            }
        }
    }
    
    return counter; 
    }

public static ArrayList<String> readInput(String input){ 
ArrayList<String> readData = new ArrayList<>(Arrays.asList(input.split(" ")));

    return readData;
    
}
Anthony
  • 51
  • 6
  • Try this' userInput.get(i).equals(fileList.get(j))' – nobalG Jan 03 '21 at 19:12
  • Hello! The problem is in using `==` to compare instances of `String`. In Java, for classes (starting with UpperCase) you need to use `object.equals(other)`. You can (and should) use `==` for primitive types - `char`, `int`, `long`, `double` etc. Do not get confused that `==` sometimes works with Strings, that's a detail you do not need to worry about right now, just use `equals()` from now on and you'll be fine. – Petr Janeček Jan 03 '21 at 19:14

0 Answers0