[英]How do I fix an “incompatible types” error in my Java code using 2-d arrays?
I'm getting a compile error that says "incompatible types" in my for loop below. 我在下面的for循环中收到一个编译错误,上面写着“不兼容的类型”。 My array is 2-d array of type int and each element, "i", is delclared as an int as well so I really don't see why I'm getting this error.
我的数组是int类型的二维数组,每个元素“i”都被声明为int,所以我真的不明白为什么我会收到这个错误。
import java.util.ArrayList;
public class Square
{
ArrayList <Integer> numbers;
int[][] squares;
private int row;
private int col;
public Square()
{
numbers = new ArrayList <Integer>();
squares = new int[row][col];
}
public void add(int i)
{
numbers.add(i);
}
public boolean isSquare()
{
double squareSize = Math.sqrt(numbers.size());
if(squareSize % 1 == 0)
{
return true;
}
else if(squareSize % 1 != 0)
{
return false;
}
}
public boolean isUnique()
{
for(int i: squares)//THIS IS WHERE I AM GETTING AN COMPILE ERROR
{
int occurences = Collections.frequency(squares, i);
if(occurrences > 1)
{
return false;
}
else
{
return true;
}
}
}
Because squares
is a int[][]
, the elements of squares
are of type int[]
, not int
. 因为
squares
是int[][]
,所以squares
的元素是int[]
类型,而不是int
。
To extract elements from such a 2D array, you'll need two nested for
loops: 要从这样的2D数组中提取元素,您需要两个嵌套的
for
循环:
for (int[] row : squares)
{
for (int i : row)
{
// Process the value here.
}
}
Aside from the fix of @RGettman, 除了@RGettman的修复,
You're using frequecy
incorrectly 你错误地使用
frequecy
int occurences = Collections.frequency(squares, i);
The first argument must be a Collection, such as ArrayList
. 第一个参数必须是Collection,例如
ArrayList
。 You're to pass an array. 你要传递一个数组。
Try this 尝试这个
int occurences = Collections.frequency(Arrays.asList(squares), i);
Handling two dimensional arrays, you must initiate 处理二维数组时,必须启动
int [][] squares = new int[row][col];
instead of squares = new int[row][col]; 而不是square = new int [row] [col];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.