laetee
laetee

Reputation: 41

Print the parameter of an object

WordDef is an object that accepts String word, and String definition as parameters. dictionary is an ArrayList of WordDef objects. I need to print out just the definition parameter based on the word the user inputs. This is what I have tried:

//in a separate class
public String toString() {

return word + "\t" + definition;
}
String d = "";
System.out.println("Enter the word you would like to see the definition of: "); 
String w = reader.nextLine();
            for(int x = 0; x < dictionary.size(); x++) {
                if(dictionary.get(x).equals(w)) {

                    d.toString(); //I know this wouldn't work but I was trying to see if anything would print at all

                }
                System.out.println("The definition for " + w + " is: " + d.toString());

I'm unsure how to search for specific parameters of an object. Thanks

Upvotes: 0

Views: 59

Answers (2)

avr_dude
avr_dude

Reputation: 242

The below code works assuming there is a getter for definition class member.

System.out.println("Enter the word you would like to see the definition of: "); 
String w = reader.nextLine();
for(int x = 0; x < dictionary.size(); x++) {
    if(dictionary.get(x).word.equals(w)) {
      System.out.println("The definition for " + w + " is: " + dictionary.get(x).getDefinition());            
    }
}

If WordDef class is somewhat like this :

public  class WordDef {
    private String word;
    private String definition ;

    public Student(String word, String definition){
        this.word=word;
        this.definition=definition;
    }

    @Override
    public String toString(){
        return "Word : "+word+", Definition : " +definition;
    }
}

You can override toString for WordDef and call System.out.println(wordDefObject) it will work.

Upvotes: 0

mattroberts
mattroberts

Reputation: 630

A Map or a HashMap would be a better way to go for efficiency and convenience, but if you want to use an ArrayList, use:

if(dictionary.get(x).getWord().equals(w) {
System.out.println(dictionary.get(x).getDefinition())
} 

getWord() and getDefinition() are just how you might have defined accessors. If word and definition are not private, you can access them directly with .word and .definition. But you probably want them to be private. You just needed the code to access properties at that index in the ArrayList.

Upvotes: 1

Related Questions