我有下一个代码片段,其中sonarint工具说我的布尔变量sentinel总是计算为true,而sentinel = true
则是一个无用的值。
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分析可能有什么问题?代码编译完美,并按预期运行。
谨致问候。
更新:
@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;
}
}
}
}
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...");
使sentinel静态或用户AtomicBoolean,这是的可见性问题