关于Java的条件运算符的基础问题
大家讲道理
大家讲道理 2017-04-17 17:25:36
0
3
314

leetcode的时候遇到个问题,简化如下:

a == b ? a : b; //有语法错误

改成下面这样自然是没有问题

c = a == b ? a : b;

网上查了下,说是Java中,条件运算符的值必须参与运算,貌似C没有这样的说法。请问是这样吗,有没有Java官方的文档中有这样的说法吗?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
刘奇

Official description here:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.8

ExpressionStatement:
StatementExpression;

StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression

Did you see that only the above expressions can be turned into statements after adding semicolons, including: assignment, self-increment and self-decrement (pre- and post-prefix), method invocation, and instance creation. Excludes conditional expressions. It is different from C/C++.

It is also clearly mentioned later:

Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements.

黄舟

Java expressions are not all statements

int a = 1;
a; // 这样也会编译错误
Ty80

This way of writing the first sentence cannot be used as a sentence alone, just like a==b; is incorrect, just change it to if(a==b){}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!