Ensures that the given value is within the range [-|maxValue|, |maxValue|]. - Java java.lang

Java examples for java.lang:Math Value

Description

Ensures that the given value is within the range [-|maxValue|, |maxValue|].

Demo Code


//package com.java2s;

public class Main {
    /**/*from w ww .j  a  v  a  2s  .co m*/
     * Ensures that the given <code>value</code> is within the range <code>[-|maxValue|, |maxValue|]</code>.  Returns the
     * given <code>value</code> if it's within the range; otherwise, returns <code>-|maxValue|</code> or
     *  <code>|maxValue|</code> as appropriate.
     */
    public static double ensureRange(final double value,
            final double maxValue) {
        final double absMaxValue = Math.abs(maxValue);

        if (value > absMaxValue) {
            return absMaxValue;
        }
        if (value < -absMaxValue) {
            return -absMaxValue;
        }

        return value;
    }

    /**
     * Ensures that the given <code>value</code> is within the range <code>[minValue, maxValue]</code>.  Returns the
     * given <code>value</code> if it's within the range; otherwise, returns <code>minValue</code> or
     *  <code>maxValue</code> as appropriate.  Performs idiot checking to make sure that <code>minValue</code> isn't
     * greater than <code>maxValue</code> (swaps the values if it is).
     */
    public static double ensureRange(final double value,
            final double minValue, final double maxValue) {
        final double min;
        final double max;

        // idiot check
        if (minValue > maxValue) {
            min = maxValue;
            max = minValue;
        } else {
            min = minValue;
            max = maxValue;
        }

        if (value > max) {
            return max;
        }
        if (value < min) {
            return min;
        }

        return value;
    }

    /**
     * Ensures that the given <code>value</code> is within the range <code>[minValue, maxValue]</code>.  Returns the
     * given <code>value</code> if it's within the range; otherwise, returns <code>minValue</code> or
     *  <code>maxValue</code> as appropriate.  Performs idiot checking to make sure that <code>minValue</code> isn't
     * greater than <code>maxValue</code> (swaps the values if it is).
     */
    public static int ensureRange(final int value, final int minValue,
            final int maxValue) {
        final int min;
        final int max;

        // idiot check
        if (minValue > maxValue) {
            min = maxValue;
            max = minValue;
        } else {
            min = minValue;
            max = maxValue;
        }

        if (value > max) {
            return max;
        }
        if (value < min) {
            return min;
        }

        return value;
    }
}

Related Tutorials