Search code examples
javaarraylistjpanelactionlistenerjtextfield

compare input to an object arraylist


I would like to compare the input from a JTextField to all the elements in a string arraylist. If the input is equal to an element in the list I would like the program to acknowledge by saying "This is in my vocabulary.", and if it is not, I would like the program to say "This is NOT in my vocabulary." In my code, I have tried getting this to work buy I always get the message "This is NOT in my vocabulary." even if the input matches an element in my list. How can I get this to work properly?

Here is my code, in it AI is where the list that is being compared is.

package Important;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import AI.*;

public class TextActions implements ActionListener{

private String hero;
private Vocabulary vocab1 = new Vocabulary();

public void actionPerformed(ActionEvent e) {

    e.getSource();
    hero = e.getActionCommand();

    if (vocab1.Adjectives.equals(hero)){
        System.out.println("This word is in my vocab");
    }else{
        System.out.println( hero + " is not in my vocab");
    }
    //CompareWords(hero);
}

public void CompareWords(String readme){

    if (vocab1.Adjectives.contains(readme)){
        //System.out.println("This word is in my vocab");
    }
}

}

Here is the Vocabulary class as requested.

package AI;

import java.util.*;

public class Vocabulary {

//String[] thoughts;
public List<String> Adjectives = new ArrayList<String>();


public void AddWord(int ArrayListNumber, String WordEntered){

    if(ArrayListNumber == 1){
    Adjectives.add(WordEntered);
    }
}

}


Solution

  • You are creating new object

    Vocabulary vocab1 = new Vocabulary();
    

    This would contain an empty Adjectives list. So, you have to first populate the Adjectives list before you do the checking as follows

    vocab1.Adjectives.contains(hero) 
    

    and use contains instead of equals.