14. |
P5. Logical Operations
The following class determines if a particular package is eligible for Unidentified Delivery Service's special Northwest Urban Rate Discount. Simplify the nested branches by using the logical operations &&, ||, and ! wherever possible.
public class Shipment { public boolean isDiscount() { boolean first; boolean second;
if (fromState.equals("OR")) { if (fromAddress.substring(0,11).equals("Rural Route") first = false; else first = true; } else if(fromState.equals("WA")) { if (fromAddress.substring(0,11).equals("Rural Route")) first = false; else first = true; } else if (fromState.equals("BC")) { if (fromAddress.substring(0,11).equals("Rural Route")) first = false; else first = true; } else first = false;
if (toState.equals("OR")) { if (toAddress.substring(0,11).equals("Rural Route")) second = false; else second = true; } else if (toState.equals("WA")) { if (toAddress.substring(0,11).equals("Rural Route")) second = false; else second = true; } else if (toState.equals("BC")) { if (toAddress.substring(0,11).equals("Rural Route")) second = false; else second = true; } else second = false;
if (first && second) return true; else return false; } . . . private String fromAddress; private String fromCity; private String fromState; private String toAddress; private String toCity; private String toState; }
Answer:
|