Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 作为大小写表达式的函数参数_Java - Fatal编程技术网

Java 作为大小写表达式的函数参数

Java 作为大小写表达式的函数参数,java,Java,下面的函数应该计算排序列表中作为参数的第i个最小元素。 我想在函数中使用“switch”表达式,而不是“if” 编译器给出以下错误:“大小写表达式必须是常量表达式” 请注意,该功能显然不完整 public int search(int[] a, int i) { ArrayList <Integer> smaller_than = new ArrayList <Integer> (); ArrayList <Integer> greater_t

下面的函数应该计算排序列表中作为参数的第i个最小元素。 我想在函数中使用“switch”表达式,而不是“if”

编译器给出以下错误:“大小写表达式必须是常量表达式”

请注意,该功能显然不完整

public int search(int[] a, int i) {
    ArrayList <Integer> smaller_than = new ArrayList <Integer> ();
    ArrayList <Integer> greater_than = new ArrayList <Integer> ();
    int pivot = a[i];

    for (int j = 0; j < a.length; j++) {
        if (a[j] < pivot) {
            smaller_than.add(a[j]);
        }

        if (a[j] >= pivot) {
            greater_than.add(a[j]);
        }
    }

    switch (smaller_than.size()) {    
        case i:
            return greater_than.get(1); <----    
    }

    return 0;
}
公共整数搜索(int[]a,int i){
ArrayList小于=新ArrayList();
ArrayList大于=新ArrayList();
int pivot=a[i];
对于(int j=0;j=枢轴){
大于加上(a[j]);
}
}
开关(小于.size()){
案例一:

返回大于.get(1);答案是你不能做你想做的事

不能对此使用
开关
语句


改用
if
语句。

编译错误是不言自明的。使用
if
来比较
i==小于.size()
你有没有这样做过?这个用法确实不是switch的目的。好吧,所以我真的必须使用if,非常感谢!正如blgt所说,编译错误是不言自明的。基本上,因为java语言规范是这样说的。深入解释:switch
中的每个
案例都有自己的mem地址ory。它不可能是动态的。谢谢@talex-我认为这说明的更多,不仅仅是“因为Java这么说”:-)深入解释事实上,伙计们,还有其他语言可以让你在案例标签中拥有你想要的任何东西,所以它确实可以归结为“因为Java这么说”。但这是一个哲学问题。