Java vs C中的三元运算符 [英] Ternary operator in java vs c

查看:59
本文介绍了Java vs C中的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个三元运算符不能在这里工作,但是在c中什么地方可以正常工作?

Why does this ternary operator doesn't works over here but where as in c it works perfectly?

import java.util.Scanner;


        class Pack {
        public static void main(String[] args) {
            System.out.println("enter a number");
            Scanner s=new Scanner(System.in);
            int i=s.nextInt();
            i%2==0?System.out.println("even"):System.out.println("odd");
        }
    }


推荐答案

因为您不能在Java中分配类似的语句。如果您像使用三元组,那么您的三元组将正常工作。

Because you can't assign a statement like that in Java. Your ternary would work if you used it like,

System.out.println(i%2==0 ? "even" : "odd");

从根本上讲,Java不是C。

Fundamentally, Java isn't C.

编辑

您在评论中问,我在哪里分配了什么东西

引用平等,关系和条件运算符(Java教程)


另一个条件运算符是?:,可以认为是if-then-else语句的简写(在本课程的控制流语句部分中进行了讨论)。此运算符也称为三元运算符,因为它使用三个操作数。在下面的示例中,该运算符应读取为:如果 someCondition true ,则分配值 value1 value 的值;否则,分配 value2 到结果

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

进一步,第15章表达式-条件运算符? :(JLS-15.25)

Further, Chapter 15. Expressions - Conditional Operator ? : (JLS-15.25) says


这是一个编译时错误第二个或第三个操作数表达式是 void 方法的调用。

这篇关于Java vs C中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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