문제

In my minecraft clone I am creating a specific type of item called food(came up with it myself).

In order to control the food amount I did this:

    if (currentFoodAmount > maxFoodAmount) {

        currentFoodAmount = maxFoodAmount;
    }

    if (currentFoodAmount < 0) {

        currentFoodAmount = 0;
    }

Is there a more efficient way?

Thanks for all the help to those who answered (the sarcasism and constructive critisism included)

p.s.s. the full code:

            if (currentFoodAmount > maxFoodAmount) {

        EntityPlayer.giveEffect(Effect.full);
        currentFoodAmount = maxFoodAmount;
    }

    if (currentFoodAmount < 0) {

        currentFoodAmount = 0;
    }

    if (currentFoodAmount == 0) {

        EntityPlayer.giveEffect(Effect.starved);
    }

        public static void tick() {

    if (!EntityPlayer.isDead) {

        --foodDecayRate;

        if (foodDecayRate == 0) {

            currentFoodAmount -= 5;
            foodDecayRate = 100;
        }
    }
}
도움이 되었습니까?

해결책 3

Less efficient, but more readable, using java Math library. Here a little example:

  currentFoodAmount = Math.min(currentFoodAmount, maxFoodAmount);
  currentFoodAmount = Math.max(currentFoodAmount, 0);

More efficient, but less readable:

  currentFoodAmount = currentFoodAmount > 0 ? (currentFoodAmount < maxFoodAmount ? currentFoodAmount : maxFoodAmount ) : 0;

다른 팁

if (currentFoodAmount > maxFoodAmount) {

    currentFoodAmount = maxFoodAmount;
} else if (currentFoodAmount < 0) {

    currentFoodAmount = 0;
}

by adding the else it will be a bit more efficient (assembly point of view) so if it run first if , will not check for second condition

I don't think there is a more efficient way that I know of. Most problems of efficiency involve creating unnecessary objects or variables that drain memory, neither of which you are doing.

You should only worry about the efficiency of small snippets of code if they are being run several times per second, i.e. on every refresh.

You only have six neat lines of code, don't be to hard on yourself.

If you want to save lines, you can come up with a pretty ugly ternary statement:

currentFoodAmount = currentFoodAmount > maxFoodAmount ? maxFoodAmount : (
    currentFoodAmount < 0 ? 0 : currentFoodAmount);

It's admittedly really hard to read, but if you're into saving lines of code, here you go.


More on Ternary

The ternary operator operates on a single conditional which evaluates to either true or false and then returns the value corresponding to the result.

Meaning if you have a statement like this:

x = y == 0 ? 1 : 2;

Your x variable will be set to 1 if y == 0. If y != 0, then x will be set to 2;

The ternary format in Java looks like this:

conditional ? trueValue : falseValue;

Do note that this technique is often frowned upon, as it often makes code difficult to read as opposed to a more verbose if/else clause.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top