现在编辑了Flowers类中的getTypeString方法,我只是得到指向对象的指针
我正在为我的一个课程开展一个项目。我以前没有和HashMap
合作过,我需要使用一个。在这个java类中,我试图打印出我已设置的完整描述。但是它不会从密钥中打印HashMap
值。我试图使用我书中的一些代码,但没有运气。
这是调用具有HashMap
:
public class Garden
{
private Gardener gardener;
private Tools tools;
private Flowers flowers;
/**
* Constructor for objects of class Garden
*/
public Garden()
{
gardener = new Gardener();
tools = new Tools();
Flowers rose;
rose = new Flowers("a beautiful red flower");
rose.setFlower("red", rose);
System.out.println(rose.fullDescription());
}
}
编辑了getTypeString方法
这是使用HashMap
的小组:
import java.util.Set;
import java.util.HashMap;
public class Flowers
{
private String fDescription;
private HashMap<String, Flowers> flowers;
/**
* Constructor for objects of class Flowers
*/
public Flowers(String fDescription)
{
this.fDescription = fDescription;
flowers = new HashMap<String, Flowers>();
}
public void setFlower(String color, Flowers type)
{
flowers.put(color, type);
}
public String flowerDescription()
{
return fDescription;
}
public String fullDescription()
{
return "The "+ getTypeString() + " is " + fDescription;
}
private String getTypeString()
{
String des = "";
Collection<Flowers> vals = flowers.values();
for(Flowers f : vals){
des += f;
}
return des;
}
}
我认为问题在于getTypeString()
功能。有人能指出我正确的方向吗?
修改
我删除了getTypeString方法并编辑了fullDescription方法:
public String fullDescription()
{
return "The "+ type + " is " + fDescription;
}
现在我正试图让'HashMap'打印出像这样的对象:
“Flower [type = type,description = Description”]“
使用thes方法:
public static void printHashMap()
{
System.out.println("hashmap: " + flowers);
}
@Override
public String toString()
{
return "Flower [type=" + type + ", description=" + fDescription ]";
}
答案 0 :(得分:0)
从您的帖子中,我所理解的是您想要打印鲜花的描述。所以我认为你可以尝试类似的东西:
private String getTypeString(){
String des = "";
Collection<String> vals = flowers.values();
for(String f : vals){
des = des + f.flowerDescription();
}
return des;
}
答案 1 :(得分:-1)
覆盖班级中的toString方法
使用以下修饰符声明toString方法并返回类型:
@Override
public String toString() {
return this.fDescription;
}
实现该方法,使其返回一个字符串。