how to call a method in another class.. Error - NullPointerException
I'm building a much larger program but this is the essential problem.
package TESTER;
publicclass Test_1{
Test_2 test;
public Test_1(Test_2 test2){
test.anropa(1);
}
publicstaticvoid main(String[] args){
Test_2 run =new Test_2();
}
}
package TESTER;
publicclass Test_2{
Test_1 t;
public Test_2(){
t =new Test_1(this);
}
publicvoid anropa(int val){
if(val==1)
System.out.println("val = 1");
elseif(val==2)
System.out.println("val = 2");
}
}
java.lang.NullPointerException
at TESTER.Test_1.<init>(Test_1.java:11)
at TESTER.Test_2.<init>(Test_2.java:10)
at TESTER.Test_1.main(Test_1.java:15)
Exception in thread "main"
Java Result: 1
How can I solve this, and (since it's a school assigment) why do I need the constructor to be Test_1(Test_2 test2) ? What does that mean?
> > package TESTER;
> public class Test_1 {
>Test_2 test;
Never initialized
>public Test_1(Test_2 test2){
>
test = test2; // I suspect
> test.anropa(1);
>
>}
>public static void main(String[] args){
> Test_2 run = new Test_2();
>}
> }
>
>
>
>
> package TESTER;
> public class Test_2 {
>Test_1 t;
>public Test_2(){
> t = new Test_1(this);
>}
>public void anropa(int val){
> if(val==1)
> System.out.println("val = 1");
> else if(val==2)
> System.out.println("val = 2");
>}
> }
>
>
> java.lang.NullPointerException
> at TESTER.Test_1.<init>(Test_1.java:11)
> at TESTER.Test_2.<init>(Test_2.java:10)
> at TESTER.Test_1.main(Test_1.java:15)
> Exception in thread "main"
> Java Result: 1
>
>
> How can I solve this, and (since it's a school
> assigment) why do I need the constructor to be
> Test_1(Test_2 test2) ? What does that mean?
Yes that did solve the problem, however, that was apparently (when I looked at my other program) not the problem I had...
let make it a bit more complicated:
package TESTER;
public class Test_1 {
Test_2 test;
public Test_1(Test_2 test){
enAnnan();
public void enAnnan();
test.anropa(1);
}
public static void main(String[] args){
Test_2 run = new Test_2();
}
}
java.lang.NullPointerException
at TESTER.Gui.enAnnan(Gui.java:13)
at TESTER.Gui.<init>(Gui.java:10)
at TESTER.Controller.<init>(Controller.java:10)
at TESTER.Gui.main(Gui.java:16)
Exception in thread "main"
Java Result: 1
Why can I call from the constructor but not from the method enAnnan() ?