سؤال

Hey guys I'm writing a program that has an abstract class 'Order' that is extended by three classes 'NonProfitOrder', 'RegularOrder', and 'OverseasOrder'. Each implement the abstract method printOrder in the abstract class.

The method accepts a string with is either "Long" or "Short"

If "Long" would look like:

Non-Profit Order

Location: CA

Total Price: 200.0

If "Short" would look like:

Non-Profit Order-Location: CA, Total Price: 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;
}

}

This is the code I have so far, which works fine to print "Long", my question is how can I get it to print depending on which "Long" or "Short" is called.

Is there a built in java method to do this? Or is there a certain way to write this string?

Thanks for any and all help!

هل كانت مفيدة؟

المحلول

a simple if statement inside the printOrder method would suffice, for example

public String printOrder(String format){
 if(format.equals("Long"){
  print and return the long version
 }else{
  print and return the short version
 }
}

نصائح أخرى

You could do something along the lines of the following:

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

}

Can you help the method having a String parameter? If so, a boolean specifing whether or not to use the long format might be easier.

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();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top