如何使用二维数组修复Java代码中的“不兼容类型”错误?

时间:2013-11-08 01:18:34

标签: java

我收到的编译错误在我的for循环中显示“不兼容的类型”。我的数组是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;
         }
       }
    }

3 个答案:

答案 0 :(得分:3)

由于squaresint[][]squares的元素属于int[],而不是int

要从这样的2D数组中提取元素,您需要两个嵌套的for循环:

for (int[] row : squares)
{
    for (int i : row)
    {
        // Process the value here.
    }
}

答案 1 :(得分:1)

除了@RGettman的修复,

您错误地使用frequecy

int occurences = Collections.frequency(squares, i);

第一个参数必须是Collection,例如ArrayList。你要传递一个数组。

试试这个

int occurences = Collections.frequency(Arrays.asList(squares), i);

答案 2 :(得分:0)

处理二维数组时,必须启动

int [][] squares = new int[row][col];

而不是square = new int [row] [col];