java - 打印对象的参数
问题描述
WordDef
是一个接受String word
和String definition
作为参数的对象。dictionary
是WordDef
对象的 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 中该索引处的属性。
推荐阅读
- python-3.x - 简单的 bot 命令在 discord.py 中不起作用
- r - 当已经使用 col.region 时,有没有办法在 lattice 包的 levelplot 函数中自定义颜色?
- flutter - Flutter Geolocator Location 不适用于真实手机
- treeview - Forge Viewer v7* 中的 SELECTION_CHANGED_EVENT 问题
- c++ - sscanf 的行为突然不同了
- c# - UWP - 默认语言是阿拉伯语 (ar-sa),但运行时是英国 (en-GB)
- python - 如何将字符串列表转换为字典列表?
- c++ - 为什么在包含 iostream 时可以使用 printf()?
- react-admin - 如何在 List 组件中使用相关的过滤器?
- arrays - 使用动态转换从表创建 postgres 视图