Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.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_Methods_Conditional Operator - Fatal编程技术网

方法上带三元运算符的Java递归

方法上带三元运算符的Java递归,java,methods,conditional-operator,Java,Methods,Conditional Operator,为什么这个代码位中使用的三元运算可以工作 public static void main(String [] args) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader( System.in ))) { String hello; while ((hello = br.readLine()) != null)

为什么这个代码位中使用的三元运算可以工作

public static void main(String [] args) throws IOException {
    try (BufferedReader br = new BufferedReader(new InputStreamReader( System.in ))) {
        String hello;
        while ((hello = br.readLine()) != null)
            System.out.println ( ( hello.matches( ".*h+.*e+.*l.*l.*o+.*" ) ) ? "YES" : "NO"); //this line works
    }
    catch ( NullPointerException xNE ) { }                  
}
但这不适用于:

private static void Print_denom( int num ) {
    if ( num > 1 ) {
        System.out.print(num + " ");
        isEven ( num ) ? Print_denom( num>>1 ) : isPrime(num) ? Print_denom(1) : Print_denom(num/Coins.div); //this one doesn't
    }               
}
?

编辑: 我想我现在明白了。如果我将第二个函数更改为:

private static int Print_denom( int num ) {
    if ( num > 1 ) {
        System.out.print(num + " ");
        return isEven ( num ) ? Print_denom( num>>1 ) : isPrime(num) ? Print_denom(1) : Print_denom(num/Coins.div);
    }
    return 0;           
}

然后它就起作用了。谢谢大家

三元运算只能用于返回表达式。在第一个代码块中,这是
“YES”
“NO”

但是,在第二段代码中,您只是使用它来调用一个方法

它不比以下任何一行更有效:

2;
"A";
someVariableName;

这里似乎回答了这个问题:。作为参考,这里是java中
表达式
语句
的定义:这是否与三元运算符在执行条件后调用的函数无效这一事实有关?将函数类型更改为int或boolean会改变这一点吗?@WChargin方法调用是表达式