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

我是Java的新手,正在尝试学习缺少if-else语句的概念。

我想出了下面的代码。 但是,代码不会编译并在if-else (即?:)语句旁边显示错误。

有人可以告诉我为什么它不起作用?

对不起,如果我的问题听起来很愚蠢。 我是Java的新手。

在此先感谢您的帮助!

 List ls1 = new LinkedList(Arrays.asList("hello", "world", "morning", "world")); Map 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. } 

三元表达

 condition ? when-true : when-false 

表达式 ,而不是语句,因此不能在需要语句的地方使用。

你可以这样写:

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

因为这是一个声明。

我不确定你要做什么,如果你试图用它的键来识别地图中某个值的出现次数那么这就是你应该做的

基本上删除提取’)’到最后,你应该总是分配三元运算符的输出。

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