java - Java 与 C 中的三元运算符

标签 java ternary-operator

<分区>

为什么这个三元运算符在这里不起作用,但在 c 中却可以完美地工作?

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 中不能像那样赋值语句。如果你像这样使用它,你的三元组就可以工作,

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

从根本上说,Java 不是 C。

编辑

你在评论中问,我在哪里分配任何东西

引用Equality, Relational, and Conditional Operators (The Java Tutorials) ,

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."

此外,Chapter 15. Expressions - Conditional Operator ? : (JLS-15.25)

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

关于java - Java 与 C 中的三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26708771/

相关文章:

java - 通过 JPA 将记录插入数据库

javascript - 这里只有三元运算符起作用

php - PHP 中的三元运算符

java - 尝试在java字符串的开头和结尾添加引号 ("")

Java 三元运算符严重评估 null

php - 三元运算符左结合性

java - 是否可以使用双引号字符作为 HashMap 键的一部分?

java - 将项目添加到数据库中

java - 扫描 HBase 中的复合键

java - double 移动小数点