The N
in main
is not the same N
as that in SomeClass
.
This is to do with the concept of scope.
The N
in main
is local to that method. In other words, it doesn't exist outside that method.
N
in the class SomeClass
is an instance variable. If you create an instance of SomeClass
, it gets its own version of N
that goes along with it.
public class SomeClass {
private static int static_member;
private int instance_member;
public void instance_method() {
// this is completely different from the other
// local_variable in static_method()
int local_variable;
static_member = 1; // legal
SomeClass.static_member = 1; // legal
instance_member = 1 // legal
this.instance_member = 1 // legal
}
public static void static_method() {
// this is completely different from the other
// local_variable in instance_method()
int local_variable;
static_member = 1; // legal
SomeClass.static_member = 1; // legal
instance_member = 1 // not legal, in a static method, there is no instance
}
}
Just because some variable has the same name, if it is in different scope, they are different variables.
Remember, that a class is like a template for objects. You make an object by instantiating the class.
You need to instantiate an instance of SomeClass
in main, and then use it. You also need to some how setup the value of N. This is typically done with a constuctor (a special function that in in charge of making instances of classes). You also need to make isValid()
a public method of your class, so that it can be called outside of your class.
public class SomeClass {
public int[][] gridArray;
private int N;
public SomeClass(int N){
this.N = N;
this.gridArray = new int[N][N];
}
public boolean isValid(int i, int j){
if (i < 0 || i >= N || j < 0 || j >= N){
System.out.println(i + " and " + j + " and "+ N);
throw new IndexOutOfBoundsException();
} else{return true;}
}
public static void main(String[] args) {
SomeClass instance = new SomeClass(5);
instance.isValid(4,4);
}
}
Finally, your logic in is valid is wrong. With an N
of 5, your upper bound checks will allow an index of 5
, but the maximum index is 4
. I've also corrected that above.