将 if 语句转换为三元运算符 - 编译器抱怨它不是语句

Converted if statement to ternary operator - compiler complains that it is not a statement

package com.myname.zed;

import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;


public class MyTest
{

    AtomicInteger counter = new AtomicInteger(100);

    @Test
    public void testAtomic()
    {
        for (int i = 1; i < 610; i++) {
            if (counter.compareAndExchange(100, 0) == 100) {
                System.out.println("trace");
            }
            else {
                counter.getAndIncrement();
            }
        }
    }

/* converted if to ternary, it is not compiling now */

    @Test
    public void testAtomic1()
    {
        for (int i = 1; i < 610; i++) {
            counter.compareAndExchange(100, 0) == 100 ? System.out.println("trace") : counter.getAndIncrement();
        }

    }

}

我只需要在 100 次中打印一次日志行。 当我使用 if 语句编写时,它按预期工作。 我将 "if" 转换为三进制,编译器抱怨它不是一个语句。

我是不是漏掉了一些非常简单的东西?有没有其他有效的方法来编写这个逻辑。

最后我做了类似的事情,每 100 次记录一次跟踪(可能不是很准确,但可以满足我的需要):

    final private ThreadLocalRandom random = ThreadLocalRandom.current();
@Test
public void testTLR()
{
    if (50 == random.nextInt(100)) {
        System.out.println("trace");
    }
    else {
        System.out.println("no trace: ");
    }
}

错误信息正确;你在那里需要一个声明,而三元表达式不是一个。 java 中的大部分内容要么是语句,要么是表达式; select 很少有东西是两者兼而有之:方法调用(包括 'weird' 构造函数调用)、赋值(a = 5 以及 a += 5)和一元运算符,例如a++).

我不确定 'efficient' 是什么意思。 if 语句速度快,性能明智,就像三元运算符一样。

如果你的意思是更短,你不需要大括号:

if (counter.compareAndExchange(100, 0) == 100) System.out.println("trace"); else counter.getAndIncrement(); – 这一切都在一条线上,但是否符合您的风格偏好是您的决定。

java中没有神奇的'allow me to treat any and all expressions as statements'选项。