【发布时间】:2020-06-12 02:33:41
【问题描述】:
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: ");
}
}
【问题讨论】:
-
if做一个语句,三元运算符做一个表达式。 Java 不会让您在需要语句的地方使用表达式(也不会生成语句)。换句话说,...?...:...在所有情况下都不能正确替换if(...) ... else ...。
标签: java if-statement compiler-errors conditional-operator