Trying to write a public method costMultiplier() that takes no arguments and returns a double

前端 未结 1 745
鱼传尺愫
鱼传尺愫 2021-01-29 16:16

The method should return 1.2 for postcodes beginning “WC1A” or “EC1A”, and 1.0 otherwise. I am not sure if I have done it right.

public double costMultiplier(fin         


        
相关标签:
1条回答
  • 2021-01-29 16:40

    Okay, a few things.

    First, for a short list of postal codes, your example code looks good. Is it not working?

    As for substring... There are two forms of substring. One takes a beginning index (starting at 0) and goes through the end of the string. The other takes a start and stop. The ending value is AFTER the last character, so for example:

    String pc = oldString.substring(0,4);
    

    This is actually convenient. When grabbing the beginning of the string, then the second parameter is the index to end at, but it's also the length. So for a 10-character string, you'll get the first four characters, at indexes 0 through 3.

    So, for your specific problem:

    public double costMultiplier(String postCode) {
        double retVal = 1.0;
        String first = postCode.trim().substring(0,4).toUpperCase();
        if (first.equals("WC1A") || first.equals("EC1A")) {
            retVal = 1.2;
        }
    
        return retVal;
    }
    

    Now, as for private versus public... It depends on who is going to call it. Is this method only for internal use? Then make it private. If you need to be able to call it from another class, then make it public. This smells like something you could make public. Private methods are typically those that do the internals of your class's work.

    At your stage of learning, you could just make all your methods public, and start thinking about public versus private interfaces later. It's sort of advanced. But basically, think of it this way.

    Public methods are what you're exposing to the outside world. Imagine someone else using your code. Imagine you're going to have coworkers who don't want to know how your code works; they're only going to use it. Public methods are the ones they can count on. Private methods can change, and no one cares but the people working on the code.

    It's more complicated than that, but I've never seen that good of an explanation. It really is up to your experience to guide you, and right now, you don't have any experience to use as a guide.

    0 讨论(0)
提交回复
热议问题