Why my if else statement (i.e. ? : ) does not work?

前端 未结 2 1588
离开以前
离开以前 2021-01-20 16:20

I\'m new to Java and is trying to learn the concept of shorthanded if-else statement.

I have came up with the code below. However, the code wouldn\'t c

相关标签:
2条回答
  • 2021-01-20 16:58

    i'm not sure what you are trying to do, In case if you are trying to identify the number of occurances of a value in a map using its key then this is what you should do

    Basically remove the extract ')' towards the end and you should always assign the output of ternary operator.

    Integer test = i1 == null ? msi1.put(s1,1) : msi1.put(s1, i1 + 1);
    
    0 讨论(0)
  • 2021-01-20 17:04

    The ternary expression

    condition ? when-true : when-false
    

    is an expression, not a statement, so can't be used where a statement is required.

    You can write this as:

    msi1.put(s1, (i1 == null) ? i1 : i1 + 1);
    

    because this is a statement.

    0 讨论(0)
提交回复
热议问题