我正在尝试使用 android studio 开发我的第一个 android 应用程序,并且在内部类构造函数中收到一些我似乎无法摆脱的警告:
- 在 for 循环中,它警告终止条件始终为真。然而,这个 wanring 只显示内部
col
for 循环,而不显示外部row
for 循环。 - 在
grid[row][col]
的赋值中,警告数组索引[row]
越界,但不警告索引[col]
是。
我完全不明白为什么会出现警告,因为代码似乎按预期运行,但也不明白为什么警告只出现在一个 for 循环和一个索引中,而肯定任何问题也适用于另一个?非常感谢任何帮助!
private class MyInnerClass {
private final Character UNKNOWN = '.';
// State data
private String id;
private Integer grid_size;
private final Character[][] grid;
// Constructor
public MyInnerClass(String id, Integer grid_size) {
// Check the grid size is in the permitted range
String[] permitted_grid_sizes = getResources()
.getStringArray(R.array.permitted_grid_sizes);
int min_permitted_grid_size = Integer
.parseInt(permitted_grid_sizes[0]);
int max_permitted_grid_size = Integer
.parseInt(permitted_grid_sizes[permitted_grid_sizes.length - 1]);
if ((grid_size < min_permitted_grid_size) || (grid_size > max_permitted_grid_size)) {
throw new IllegalArgumentException(
"specified grid size (" + grid_size + ") out of range");
}
// Initialise metadata
this.id = id;
this.grid_size = grid_size;
// Initialise a blank grid
this.grid = new Character[this.grid_size][this.grid_size];
for (int row = 0; row < this.grid_size; row++) {
for (int col = 0; col < this.grid_size; col++) { // Gives warning "Condition 'col < this.grid_size' is always 'true'"
this.grid[row][col] = UNKNOWN; // Gives warning "Array index is out of bounds" on [row]
}
}
}
...
}
最佳答案
我认为这个问题与变量类型有关。
字段 grid_size
属于 Integer 类,您正在将它与原始类型“int”的 row
和 col
进行比较。
grid_size == row
将引用与值进行比较。
可能发生的情况是您的 IDE 正在检测此问题,但给您的警告不准确。
如果将 grid_size
更改为原始类型 int
,警告应该会消失。
关于java - "Condition is always ' 真 '"和 "Array index is out of bounds"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64953018/