1

I'm getting a compile error that says "incompatible types" in my for loop below. 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.

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;
         }
       }
    }
4

3 回答 3

2

Because squares is a int[][], the elements of squares are of type int[], not int.

To extract elements from such a 2D array, you'll need two nested for loops:

for (int[] row : squares)
{
    for (int i : row)
    {
        // Process the value here.
    }
}
于 2013-11-08T01:20:55.473 回答
1

Aside from the fix of @RGettman,

You're using frequecy incorrectly

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

The first argument must be a Collection, such as ArrayList. You're to pass an array.

Try this

int occurences = Collections.frequency(Arrays.asList(squares), i);
于 2013-11-08T01:27:09.630 回答
0

Handling two dimensional arrays, you must initiate

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

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

于 2013-11-08T01:37:49.853 回答