user2913669
user2913669

Reputation: 63

2 simple array errors?

I created a method that needs to check the range of a multidimensional array and make sure each value in the 2D array is smaller than or equal to the length of the array.

public static boolean method(int[][] solution){
        //check rows for 1-N
        for (int i=0; i < solution.length; i++){
                if (solution[i] > solution.length)
                return false; //check rows
            }

        //check columns for 1 - N
        for (int j = 0; j<solution.length; j++){
            //get a column in the one dimensional array
            int[] column = new int[solution.length];
            for (int i=0; i < solution.length; i++){
                column[i] = solution[i][j];
            }
            if (column[i] > solution.length)
                return false; //check columns

        }
    return true;
    }

However, the errors I receive are follows:

Program.java:99: error: bad operand types for binary operator '>'
                                if (solution[i] > solution.length)
                                                ^
  first type:  int[]
  second type: int
Program.java:110: error: cannot find symbol
                        if (column[i] > solution.length)
                                   ^
  symbol:   variable i
  location: class Program
2 errors

Perhaps for the first error i need to get the array value instead of comparing the array? Not sure..

Upvotes: 1

Views: 78

Answers (4)

Rahul
Rahul

Reputation: 45070

First, you can't compare an array with an int value

if (solution[i] > solution.length) // solution is a 2-d array and thus solution[i] is a 1-d array
// which can't be compared with an int value

and second, the i was declared in the for loop, and thus it's not visible outside its scope.

for (int i=0; i < solution.length; i++){
    column[i] = solution[i][j];
} // scope of i is over here
if (column[i] > solution.length) // that's why you can't access `i` here
    return false;

You either need to use j or declare the i before the for, so that you can use it after it or probably, move the if inside the inner for loop(and that seems to be the right way for your problem as well).

Upvotes: 4

Pratik Shelar
Pratik Shelar

Reputation: 3212

I suppose this much code should suffice

public static boolean method(int[][] solution) {
    // check rows for 1-N
    for (int i = 0; i < solution.length; i++) {
        for (int j = 0; j < solution[i].length; i++) {
            if (solution[i][j] > solution.length)
                return false; // check rows
        }
    }

    return true;
}

Upvotes: 0

Isuru Gunawardana
Isuru Gunawardana

Reputation: 2887

Its because, solution is a 2d array.

int[][] solution;

and to get this work it should be,

if(solution[][] > solution.length)

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You are using i outside the for loop, maybe you want to use j instead.

Upvotes: 1

Related Questions