打印字符串的“长”或“短”形式

时间:2013-09-11 21:43:50

标签: java format abstract long-integer short

嘿伙计们我正在编写一个程序,它有一个抽象类'Order',由三个类'NonProfitOrder','RegularOrder'和'OverseasOrder'扩展。每个都在抽象类中实现抽象方法printOrder。

该方法接受一个字符串,其长度为“Long”或“Short”

如果“Long”看起来像:

非营利订单

位置:CA

总价格: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方法来执行此操作?或者是否有某种方式来写这个字符串?

感谢您的帮助!

3 个答案:

答案 0 :(得分: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
 }
}

答案 1 :(得分: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 "";

}

答案 2 :(得分:0)

你能帮助那个String参数的方法吗?如果是这样,指定是否使用长格式的布尔值可能更容易。

public String printOrder(boolean longFormat) {
    if (longFormat) {
        return "Non-Profit Order" + "\nLocation: " + getLocation() +  "\nTotal Price: " + getPrice();
    }
    return "Non-Profit Order Location: " + getLocation() +  " Total Price: " + getPrice();
}