0

したがって、ローカルデータ構造には次のものがあります

DataStructure ds = new DataStructure();

    //Examples to put in the Data Structure "ds"
    ds.menu_item.put("Pizza", new DescItems("A Pizza",2.50,4));
    ds.menu_item.put("Hot Dog", new DescItems("A yummy hot dog",3.50, 3));
    ds.menu_item.put("Corn Dog", new DescItems("A corny dog",3.00));
    ds.menu_item.put("Unknown Dish", new DescItems(3.25));

DataStructureクラスには、次のようなLinkedHashMap実装があります。

LinkedHashMap<String, DescItems> menu_item = new LinkedHashMap<String, DescItems>();

そして最後に、DescItemsクラスは

public final String itemDescription;
public final double itemPrice;
public final double itemRating;

public DescItems(String itemDescription, double itemPrice, double itemRating){
    this.itemDescription = itemDescription;
    this.itemPrice = itemPrice;
    this.itemRating = itemRating;
}

itemDescriptionおよび/またはitemRatingを考慮しない他のコンストラクターがあります

値に0以外のitemRatingがあるかどうかを確認するメソッドを適用しようとしています(0は評価がないことを示します)

しかし、具体的に私はこの問題に遭遇しました:

DescItems getC1 = (DescItems)ds.menu_item.get("Pizza");
    System.out.println(getC1.toString());

DescItems@142D091などの参照情報のみを出力します

オブジェクトを参照する代わりに、特定のオブジェクト変数を取得するにはどうすればよいですか?

4

3 に答える 3

1

クラスのtoString()メソッドをオーバーライドできます。DescItems例えば:

public class DescItems {
    . . .

    @Override
    public String toString() {
        // whatever you want here
        return String.format("%1$s (price: $%2$.2f; rating: %3$f)",
            itemDescription, itemPrice, itemRating);
    }
}

のデフォルトの実装はtoString()、表示されているようなオブジェクト識別文字列を返します。

別の方法は、必要なフィールドを正確に印刷することです。

System.out.println(getC1.itemDescription);
于 2012-12-13T00:30:14.083 に答える
1

toString()でメソッドをオーバーライドする必要がありますDescItems

このようなもの:

@Override
public String toString() {
     return itemDescription + " " + itemPrice + currencySymbol + " (" + itemRating + ")";
}
于 2012-12-13T00:30:20.193 に答える
0

必要なテキストを返すには、toString()メソッドをオーバーライドする必要があります。

于 2012-12-13T00:31:08.210 に答える