这是我用java的第二天,我无法弄清楚私有方法中公共变量为0的原因。代码如下:
public class SomeClass {
public int[][] gridArray;
private int N;
public methodOne(int N){
gridArray = new int[N][N];
}
private boolean isValid(int i, int j){
if (i < 0 || i > N || j < 0 || j > N){
StdOut.println(i + " and " + j + " and "+ N);
throw new java.lang.IndexOutOfBoundsException();
} else{return true;}
}
public static void main(String[] args) {
int N = 5;
// some code for getting indices
}
所以,我创建一个数组,并输入索引,并检查这些索引是否有效,或者是否超出范围。我总是得到异常,因为在isValid方法中N是0,尽管在main中声明。
答案 0 :(得分:3)
N
中的main
与N
中的SomeClass
不同。
这与范围的概念有关。
N
中的main
是该方法的本地。换句话说,它不存在于该方法之外。
N
中的 SomeClass
是一个实例变量。如果您创建SomeClass
的实例,它会获得自己的N
版本。
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
}
}
仅仅因为某个变量具有相同的名称,如果它在不同的范围内,则它们是不同的变量。
请记住,类就像是对象的模板。您通过实例化类来创建对象。
您需要在main中实例化SomeClass
的实例,然后使用它。您还需要设置N的值。这通常使用一个constuctor(一个负责制作类实例的特殊函数)来完成。您还需要使isValid()
成为您班级的公共方法,以便可以在班级之外调用它。
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);
}
}
最后,你的逻辑有效是错误的。如果N
为5,则上限检查将允许索引为5
,但最大索引为4
。我也纠正了上述情况。
答案 1 :(得分:0)
你的问题是,范围不同:
在构造函数中使用了int N
参数。因此编译器使用此变量来初始化数组。
该类的private int N
字段未实例化。因此,isValid
方法使用类字段的默认值。
您正在实例化另一个变量的主要功能
由此产生的问题是,您在代码中实际上有3个不同的N
。
如果你将this.N = N
放在methodOne
内并给它一个返回类型(void
),一切都应该没问题
答案 2 :(得分:0)
差异是变量,定义为实例变量和方法变量。
private int N;
此变量N
被定义为字段memmber(直接在类内),它是一个实例变量。
int N = 5;
这个int N
是在main方法下定义的,它是一个方法变量。
两个变量都有不同的范围,并且不能共享相同的值。