方法上带三元运算符的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方法调用是表达式