为什么我的if else语句(即?:)不起作用? [英] Why my if else statement (i.e. ? : ) does not work?

查看:351
本文介绍了为什么我的if else语句(即?:)不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I have came up with the code below. However, the code wouldn't compile and displays an error beside the if-else (i.e. ? : ) statement.

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

Could someone please tell me why is it not working?

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

Sorry if my question sounds very silly to some of you. I'm new to 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.
}


推荐答案

三元表达式

condition ? when-true : when-false

表达式,而非声明,所以不能在需要声明的地方使用。

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

你可以写成:

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

因为这是一个声明。

这篇关于为什么我的if else语句(即?:)不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆