我有下一个代码片段,其中 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;
}
}
}
}