3

我有下一个代码片段,其中 sonarlint 工具说我的布尔变量 sentinel 总是计算为真,sentinel = true这是一个无用的 asingment。

import static java.lang.System.*;

public class Sentinel {

    private static final int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    public static void main(String[] args) {
        boolean sentinel = false;
        int counter = 0;
        while (!sentinel) {
            out.println( "Counter: " + counter);
            out.println( "Array index: " + array[counter] );
            counter++;
            if ( counter == array.length - 1 ) {
                out.println( "End of the array reached" );
                sentinel = true;
                out.println( "Breaking..." );
                break;
            }
        }
    }
}

sonarlint analisys 可能有什么问题?代码完美编译并按预期运行。

问候。

更新:

@kkk 提供了两个有价值的答案。见下文,但我在这里放了我更喜欢的一个:

import java.util.concurrent.atomic.AtomicBoolean;

import static java.lang.System.*;

public class Sentinel {

    private static final int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    public static void main(String[] args) {
        AtomicBoolean sentinel = new AtomicBoolean(false);
        int counter = 0;
        while ( !sentinel.get() ) {
            out.println( "Counter: " + counter);
            out.println( "Array index: " + array[counter] );
            counter++;
            if ( counter == array.length - 1 ) {
                out.println( "Counter limit reached" );
                sentinel.set( true );
                out.println( "Breaking..." );
                break;
            }
        }
    }
}
4

2 回答 2

1

所做的更改sentinel = true;永远不会被 看到while (!sentinel)。那是因为 break 语句。

for话虽如此,您的代码使用循环要简单得多。你while只是让它变得复杂。

for(int counter = 0; counter < array.length; counter++) {
    out.println("Counter: " + counter);
    out.println("Array index: " + array[counter]);
    if (counter == array.length - 1) {
        out.println("End of the array reached");
        out.println("Breaking...");
    }
}

或者,更好的是,counter == array.length - 1在循环之后执行操作

for(int counter = 0; counter < array.length; counter++) {
    out.println("Counter: " + counter);
    out.println("Array index: " + array[counter]);
}
out.println("End of the array reached");
out.println("Breaking...");
于 2021-12-22T07:57:25.437 回答
-1

使哨兵静态或用户原子布尔,这是可见性问题

于 2021-12-22T07:51:25.980 回答