简体   繁体   中英

return (n > 2) ? n = 5 : n = 4; doesn't work?

Why does this return an error

return (n > 2) ? n = 5 : n = 4;

but this does not

return (n > 2) ? n = 5 : n + 4;

Should it not be able to return n depending on either case?

The code you have can't be compiled because the ternary operator has a higher operator precedence than the assignment operator:

Operator Precedence

  1. postfix ( expr++ expr-- )
  2. unary ( ++expr --expr +expr -expr ~ ! )

...

  1. ternary ( ? : )
  2. assignment ( = += -= *= /= %= &= ^= |= <<= >>= >>>= )

When parsing the code

(n > 2) ? n = 5 : n = 4;

it will parse it like this:

(n > 2) ? n = 5 : n     // ternary operator
                    = 4 // assignment operator

This would result in pseudo code like this:

someResultValue 
                = value;

That will not work and you get compile errors like:

'Syntax error on token "=", <= expected'

or

'Type mismatch: cannot convert from Object & Comparable<?> & Serializable to int'.

You can use parentheses to let java see the third argument of the ternary operator as n = 4 . The code would look like this:

return (n > 2) ? n = 5 : (n = 4);

I think you may have any syntax error. I tried that in chrome JS console and worked fine!! 问题的解答

Update: Some people argued in comments that I didn't write function so I wrote in functional format and got the same result!在此处输入图像描述

syntax: condition? expression1: expression2;

Try this

public class Solution {
    public static void main(String[] args) throws IOException {
       int a = 10;
       int b = (a>5)?a=5:0;
       System.out.println("a = "+ a);
       System.out.println("b = "+b);
       
    }
}

output: a = 5 b = 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM