[英]Access variable within exception from another class
I need to validate if an exception is true but from another class 我需要验证异常是否为真,但来自另一个类
i have 2 classes class_a
and class_b
我有2个班级class_a
和class_b
Here are the classes: 这些是类:
public class Class_a {
static boolean pru = false;
public static boolean Getpru() {
return pru;
}
public static void Setpru(boolean setAValue) {
pru = setAValue;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Class_a a = new Class_a();
Class_b b = new Class_b();
int entr = 0;
try {
System.out.println("Enter a number");
entr = scan.nextInt();
} catch (Exception e) {
a.Setpru(true);
}
b.val();
} }
i'm changing the value of pru
to true when it falls in the exception 当它出现异常时,我pru
的值pru
为true
Here's the second class 这是第二节课
public class Class_b {
Class_a a = new Class_a();
public void val() {
if (a.Getpru()) {
System.out.println("There is a misktake in the value");
} else {
System.out.println("The value is correct");
}
}
} }
The problem i have is that in class_b
the pru
value does not match the class_a
boolean value 我的问题是,在class_b
, pru
值与class_a
布尔值不匹配
Your are using wrong instances, the first time you check the "pru" value you are using "instance 1" of "Class_a" but when you validate inside "Class_b" your are using a brand new instance... try the following: 您使用的是错误的实例,第一次检查“ pru”值时,您使用的是“ Class_a”的“实例1”,但是当您在“ Class_b”中进行验证时,则使用的是全新的实例...请尝试以下操作:
Class_a Class_a
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Class_a a = new Class_a();
Class_b b = new Class_b();
int entr = 0;
try {
System.out.println("Enter a number");
entr = scan.nextInt();
} catch (Exception e) {
a.Setpru(true);
}
b.val(a);
}
Class_b Class_b
public class Class_b {
public void val(Class_a a) {
if (a.Getpru()) {
System.out.println("There is a misktake in the value");
} else {
System.out.println("The value is correct");
}
}
}
That way "Class_b" will use the same "Class_a" instance. 这样,“ Class_b”将使用相同的“ Class_a”实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.