简体   繁体   English

为什么我的 if else 语句(即 ? : )不起作用?

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

I'm new to Java and is trying to learn the concept of shorthanded if-else statement.我是 Java 新手,正在尝试学习简写if-else语句的概念。

I have came up with the code below.我想出了下面的代码。 However, the code wouldn't compile and displays an error beside the if-else (ie ? : ) statement.但是,代码不会编译并在if-else (即 ? : )语句旁边显示错误。

Could someone please tell me why is it not working?有人可以告诉我为什么它不起作用吗?

Sorry if my question sounds very silly to some of you.对不起,如果我的问题对你们中的一些人来说听起来很愚蠢。 I'm new to Java.我是 Java 新手。

Thanks in advance for any help!在此先感谢您的帮助!

List<String> ls1 = new LinkedList<>(Arrays.asList("hello", "world", "morning", "world"));
Map<String, Integer> msi1 = new LinkedHashMap<>();

for(String s1 : ls1){
    Integer i1 = msi1.get(s1);
    i1 == null ? msi1.put(s1, i1) : msi1.put(s1, i1 + 1));//why can't I use the short if-else statement like this.
}

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.因为这是一个声明。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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