2

こんにちは、「NonProfitOrder」、「RegularOrder」、および「OverseasOrder」の 3 つのクラスによって拡張された抽象クラス「Order」を持つプログラムを作成しています。それぞれが、抽象クラスで抽象メソッド printOrder を実装します。

このメソッドは、「Long」または「Short」のいずれかの文字列を受け入れます

「長い」が次のようになる場合:

非営利の注文

場所: カリフォルニア州

合計金額: 200.0

「Short」が次のようになる場合:

非営利の注文場所: CA、合計金額: 200.0

public class NonProfitOrder extends Order {

public NonProfitOrder(double price, String location) {
    super(price, location);
}

public double calculateBill() {
    return getPrice();
}

public String printOrder(String format){
    String Long = "Non-Profit Order" + "\nLocation: " + getLocation() +  "\nTotal Price: " + getPrice();
    return Long;
}

}

これは私がこれまで持っていたコードで、「Long」を印刷するのに問題なく動作します。私の質問は、「Long」または「Short」のどちらが呼び出されるかに応じて、どのように印刷できるかです。

これを行う組み込みのJavaメソッドはありますか?または、この文字列を記述する特定の方法はありますか?

助けてくれてありがとう!

4

3 に答える 3

1

たとえば、printOrder メソッド内の単純な if ステートメントで十分です。

public String printOrder(String format){
 if(format.equals("Long"){
  print and return the long version
 }else{
  print and return the short version
 }
}
于 2013-09-11T21:53:59.380 に答える
0

次の行に沿って何かを行うことができます。

public String printOrder(String format){
    String orderDetailsLong = "Non-Profit Order" + "\nLocation: " + getLocation()     +  "\nTotal Price: " + getPrice();
    String orderDetailsShort = "Non-Profit Order" + " Location: " + getLocation() +  " Total Price: " + getPrice();

    if(format.toLowerCase()=="long")
    {
       return orderDetailsLong;
    }

    if(format.toLowerCase()=="short")
    {
        return orderDetailsShort;
    }

     // you might want to handle the fact that the supplied string might not be what you expected 
    return "";

}
于 2013-09-11T21:54:56.487 に答える