简体   繁体   English

将 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();
        }

    }

}

I need to print a log line only once out of 100 times.我只需要打印 100 次中的一次日志行。 It works as expected when I write using if statement.当我使用 if 语句编写时,它按预期工作。 I converted "if" to ternary, compiler complains it is not a statement.我将“if”转换为三元,编译器抱怨它不是一个语句。

Am I missing something really simple thing here?我在这里错过了一些非常简单的事情吗? And is there any other efficient way of writing this logic.有没有其他有效的方式来编写这个逻辑。

And I ended up doing similar to this to log trace once every 100th time(may not be very accurate, but it is fine with my needs):我最终做了与此类似的操作,每 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: ");
    }
}

The error message is on point;错误信息很重要; you need a statement there, and the ternary expression isn't one.您需要在那里声明,而三元表达式不是一个。 Most things in java are either a statement or an expression; java中的大多数东西要么是语句,要么是表达式; a select few things are both: method invocations (including 'weird' ones such as constructor invocations), assignments ( a = 5 , as well as a += 5 ), and unary operators such as a++ ).选择的几个东西都是:方法调用(包括“奇怪”的调用,例如构造函数调用)、赋值( a = 5 ,以及a += 5 )和一元运算符,例如a++ )。

I'm not sure what you mean by 'efficient'.我不确定你所说的“高效”是什么意思。 An if statement as is fast, performance wise, as a ternary operator would be. if 语句速度快,性能好,就像三元运算符一样。

If you mean shorter, you don't need the braces:如果您的意思是更短,则不需要大括号:

if (counter.compareAndExchange(100, 0) == 100) System.out.println("trace"); else counter.getAndIncrement(); – that all fits on one line, but whether that fits your style preferences is your decision. – 所有这些都适合一条线,但是否适合您的风格偏好是您的决定。

There is no magic 'allow me to treat any and all expressions as statements' option in java. java中没有神奇的“允许我将任何和所有表达式视为语句”选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM