WordDef是接受String wordString definition作为参数的对象。 dictionaryWordDef对象的ArrayList。我只需要根据用户输入的definition打印word参数。这是我尝试过的:

//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());


我不确定如何搜索对象的特定参数。谢谢

最佳答案

Map或HashMap是提高效率和便利性的更好方法,但是如果您想使用ArrayList,请使用:

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


getWord()和getDefinition()就是定义访问器的方式。如果单词和定义不是私有的,则可以直接使用.word和.definition访问它们。但是您可能希望它们是私有的。
您只需要代码即可访问ArrayList中该索引处的属性。

关于java - 打印对象的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59834236/

10-14 16:52
查看更多