HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Issue a citation based on speed, with lenience for your birthday

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
birthdaylenienceyourwithissueforbasedcitationspeed

Problem

You are driving a little too fast, and a police officer stops you. Write
code to compute the result, encoded as an int value: 0=no ticket, 1=small
ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is
between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the
result is 2. Unless it is your birthday -- on that day, your speed can be
5 higher in all cases.

public int caughtSpeeding(int speed, boolean isBirthday) {
if(isBirthday) {
    if(speed <= 65) {
        return 0;
    } else if(66 <= speed && speed <= 85) {
        return 1;
    } else if(86 <=  speed) {
        return 2;
    }
}

if(speed <= 60) {
    return 0;
} else if(61 <= speed && speed <= 80) {
    return 1;
} else {
    return 2;
}}

Solution

This function should probably be static, since it does not rely on any instance variables.

On your birthday, your speed can be 5 higher in all cases — so don't make three more cases for the birthday.

If you have already determined that the speed is not <= 60, then there is no point in testing 61 <= speed — that will always be the case.

Since all three branches similarly return an expression, I would use a ternary statement.

public static int caughtSpeeding(int speed, boolean isBirthday) {
    int birthdayAdjustedSpeed = isBirthday ? speed - 5 : speed;
    return (birthdayAdjustedSpeed <= 60) ? 0 :
           (birthdayAdjustedSpeed <= 80) ? 1 :
                                           2;
}

Code Snippets

public static int caughtSpeeding(int speed, boolean isBirthday) {
    int birthdayAdjustedSpeed = isBirthday ? speed - 5 : speed;
    return (birthdayAdjustedSpeed <= 60) ? 0 :
           (birthdayAdjustedSpeed <= 80) ? 1 :
                                           2;
}

Context

StackExchange Code Review Q#159774, answer score: 4

Revisions (0)

No revisions yet.