jeudi 27 février 2020

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. It works as expected when I write using if statement. I converted "if" to ternary, compiler complains it is not a statement.

Am I missing something really simple thing here? And is there any other efficient way of writing this logic.

Aucun commentaire:

Enregistrer un commentaire