如何設(shè)置Java邊界值

小樊
83
2024-09-09 11:49:06

在 Java 中,設(shè)置邊界值通常是為了確保數(shù)據(jù)在某個(gè)范圍內(nèi)

  1. 使用 Math.min()Math.max() 方法:
public class BoundaryValueExample {
    public static void main(String[] args) {
        int value = 10;
        int lowerBound = 5;
        int upperBound = 8;

        int boundedValue = Math.min(Math.max(value, lowerBound), upperBound);
        System.out.println("Bounded value: " + boundedValue);
    }
}
  1. 使用條件語(yǔ)句(如 if-else):
public class BoundaryValueExample {
    public static void main(String[] args) {
        int value = 10;
        int lowerBound = 5;
        int upperBound = 8;

        int boundedValue;
        if (value< lowerBound) {
            boundedValue = lowerBound;
        } else if (value > upperBound) {
            boundedValue = upperBound;
        } else {
            boundedValue = value;
        }
        System.out.println("Bounded value: " + boundedValue);
    }
}
  1. 自定義方法:
public class BoundaryValueExample {
    public static void main(String[] args) {
        int value = 10;
        int lowerBound = 5;
        int upperBound = 8;

        int boundedValue = boundValue(value, lowerBound, upperBound);
        System.out.println("Bounded value: " + boundedValue);
    }

    private static int boundValue(int value, int lowerBound, int upperBound) {
        return Math.min(Math.max(value, lowerBound), upperBound);
    }
}

這些示例都將確保 boundedValuelowerBoundupperBound 之間。如果 value 小于 lowerBound,則 boundedValue 將等于 lowerBound;如果 value 大于 upperBound,則 boundedValue 將等于 upperBound;否則,boundedValue 將等于 value。

0