首页 > 解决方案 > 打印对象的参数

问题描述

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

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

标签: javaconstructor

解决方案


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

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

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


推荐阅读