0

Why does the ternary operation used in this code bit work?

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 ) { }                  
}

But it doesn't work with this:

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
    }               
}

?

EDIT: I think I understand now. If I change the 2nd function to something like:

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;           
}

then it works. Thanks everyone

smac89
  • 39,374
  • 15
  • 132
  • 179
  • Seems like this was answered here: http://stackoverflow.com/a/9451021. And, for reference, here's the definition of `expression` and `statement` in java: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html – rliu May 01 '13 at 02:50

1 Answers1

2

The ternary operation can only be used to return an expression. In the first block of code, this is either "YES" or "NO".

However, in the second block of code, you are simply using it to invoke a method.

It's no more valid than any of the following lines:

2;
"A";
someVariableName;
wchargin
  • 15,589
  • 12
  • 71
  • 110
  • Does this have anything to do with the fact that the function the ternary operator is calling, after the condition is executed is void? And does changing the type of the function to something like int or boolean change this? – smac89 May 01 '13 at 03:01
  • @WChargin method calls are expressions – rolfl May 01 '13 at 03:05