Java &引用;条件始终为';正确'&引用;及;数组索引超出范围“;警告
我正在尝试使用android studio开发我的第一个android应用程序,在一个内部类构造函数中,我收到了几个似乎无法摆脱的警告:Java &引用;条件始终为';正确'&引用;及;数组索引超出范围“;警告,java,android,android-studio,for-loop,indexoutofboundsexception,Java,Android,Android Studio,For Loop,Indexoutofboundsexception,我正在尝试使用android studio开发我的第一个android应用程序,在一个内部类构造函数中,我收到了几个似乎无法摆脱的警告: 在for循环中,它警告终止条件始终为true。但是,此wanring仅显示内部列for循环,而不显示外部行for循环 在网格[row][col]的赋值中,它警告数组索引[row]超出范围,但不是索引[col]超出范围 我不明白为什么会出现警告,因为代码似乎按预期运行,但为什么警告只针对一个for循环和一个索引出现,而任何问题肯定也会应用于另一个?非常感谢您的帮
列for循环,而不显示外部行for循环
网格[row][col]
的赋值中,它警告数组索引[row]
超出范围,但不是索引[col]
超出范围私有类MyInnerClass{
私有最终字符未知=';
//状态数据
私有字符串id;
私有整数网格大小;
私有最终字符[][]网格;
//建造师
公共MyInnerClass(字符串id,整数网格大小){
//检查网格大小是否在允许范围内
字符串[]允许的网格大小=getResources()
.getStringArray(R.array.允许的网格大小);
整数最小允许网格大小=整数
.parseInt(允许的网格大小[0]);
整数最大允许网格大小=整数
.parseInt(允许的网格大小[允许的网格大小.长度-1]);
如果((网格大小<最小允许网格大小)| |(网格大小>最大允许网格大小)){
抛出新的IllegalArgumentException(
“指定的网格大小(“+网格大小+”)超出范围”);
}
//初始化元数据
this.id=id;
this.grid\u size=网格大小;
//初始化空白网格
this.grid=新字符[this.grid\u size][this.grid\u size];
对于(int row=0;row
我认为这个问题与变量类型有关。
字段grid\u size
为整数类,您将其与基本类型为“int”的row
和col
进行比较
网格大小==行
将引用与值进行比较
可能发生的情况是,您的IDE检测到了这个问题,但给出了不准确的警告
如果将网格大小更改为基本类型,则警告应该消失。重新启动Android Studio时问题是否仍然存在?乍一看,这似乎是他们这边的一个问题。这似乎是Android Studio中的一个bug。将字段
grid\u size
从private Integer grid\u size代码>至专用整数网格大小代码>删除警告。
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]
}
}
}
...
}