如何在Java中定义"范围"?

T14*_*145 0 java integer boolean case range

我有一大块代码需要确定给定的整数是否在一组其他整数之间.我还希望在案例陈述中提到这一点,以便在任何地方都没有多余的if..else陈述.这是一些代码:

switch (copies) {
        case copies >= 0 && copies <= 99: copyPrice = 0.30; break;
        case copies >= 100 && copies <= 499: copyPrice = 0.28; break;
        case copies >= 500 && copies <= 749: copyPrice = 0.27; break;
        case copies >= 750 && copies <= 1000: copyPrice = 0.26; break;
        case copies > 1000: copies = 0.25; break;
    }
Run Code Online (Sandbox Code Playgroud)

where copies是一个整数,copyPrice是一个double.我得到几个错误,说它希望收到一个整数,但得到一个布尔值.设置它的最佳(或最佳)方法是什么?任何帮助是极大的赞赏!

Lui*_*oza 7

这一行(和类似):

case copies >= 0 && copies <= 99:
Run Code Online (Sandbox Code Playgroud)

因为它给出了一个返回一个编译器错误boolean,但编译器期望的int,因为copy被声明为int.

解决此问题的一种方法是使用具有所需排名的数组,并为找到的索引设置switch语句:

public double calculateCopyPrice(int copies) {
    int[] range = { 99, 499, 749, 1000 };
    double copyPrice = 0;
    int index = -1;
    for (int i = 0; i < range.length; i++) {
        if (range[i] >= copies) {
            index = i;
            break;
        }
    }
    switch (index) {
        case 0: copyPrice = 0.30; break;
        case 1: copyPrice = 0.28; break;
        case 2: copyPrice = 0.27; break;
        case 3: copyPrice = 0.26; break;
        default: copyPrice = 0.25; break; 
    }
    //probably more logic here...
    return copyPrice;
}
Run Code Online (Sandbox Code Playgroud)

经过一些测试,我找到了一个更灵活的解决方案,使用a TreeMap<Integer, Double>允许你有一个范围的物种(你正在寻找的东西)并通过使用TreeMap#ceilingEntry以下方式简化搜索:

//TreeMap to store the "ranges"
TreeMap<Integer, Double> theMap = new TreeMap<Integer, Double>();
//add the data
theMap.put(99, 0.3);
theMap.put(499, 0.28);
theMap.put(749, 0.27);
theMap.put(1000, 0.26);
//the "default" value for max entries
theMap.put(Integer.MAX_VALUE, 0.25);
//testing the solution
Double ex1 = theMap.ceilingEntry(50).getValue();
Double ex2 = theMap.ceilingEntry(500).getValue();
Double ex3 = theMap.ceilingEntry(5000).getValue();
Double ex4 = theMap.ceilingEntry(100).getValue();
System.out.println(ex1);
System.out.println(ex2);
System.out.println(ex3);
System.out.println(ex4);
Run Code Online (Sandbox Code Playgroud)