【问题标题】:Printing 'long' or 'short' form of a string打印字符串的“长”或“短”形式
【发布时间】:2013-09-11 21:43:49
【问题描述】:

大家好,我正在编写一个程序,它有一个抽象类“Order”,该类由三个类“NonProfitOrder”、“RegularOrder”和“OverseasOrder”扩展。每个都实现了抽象类中的抽象方法printOrder。

该方法接受“长”或“短”的字符串

如果“长”看起来像:

非营利组织

地点:加州

总价:200.0

如果“短”看起来像:

非营利订单-地点: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 方法来执行此操作?或者有什么方法可以写这个字符串?

感谢您的所有帮助!

【问题讨论】:

  • 为什么不使用 .equals() 方法的 if 语句?例如if (format.equals("Long"){ print long version} else {print short}

标签: java format abstract long-integer short


【解决方案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
 }
}

【讨论】:

  • 感谢这个完美的作品,我把它复杂化了。
  • 如果你想冒险看看三元运算符。只是一种不同的风格,你可能会发现在不同的场景中有用:)
【解决方案2】:

您可以按照以下方式做一些事情:

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 "";

}

【讨论】:

    【解决方案3】:

    你能帮助具有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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多