0

I am trying to get the following program to run. However, a NullPointerException is showing up. I have debug my code every step of the way thus far. It seems that the null pointer exception comes about after I implement the numA.add() in main.

Main.java

public class Main {

    public static void main(String[]args){

        NumberSystem numA = new NumberSystem(new Number(20),new Number(10));
        numA.add();
        System.out.println(numA.getResult().toString());
    }
}

NumberSystem.java

public class NumberSystem {

    private Number n1,n2,result;

    public NumberSystem(){
        n1 = new Number(0);
        n2 = new Number(0);
        result = new Number(0);
    }

    public NumberSystem(Number n1,Number n2){       
        n1 = new Number();
        n2 = new Number();
        result = new Number(0);
    }   

    public NumberSystem(NumberSystem n){
        n1 = new Number(n.n1);
        n2 = new Number(n.n2);
        result = new Number(n.result);
    }

    public Number getN1(){
        return n1 = new Number(n1.getNum());
    }

    public Number getN2(){
        return n2 = new Number(n2.getNum());
    }

    public Number getResult(){
        return result = new Number(result.getNum());
    }

    public void setN1(int n1Value){
        if (n1Value != 0) n1 = new Number(n1Value);
    }

    public void setN2(int n2Value){
        if (n2Value != 0) n2 = new Number(n2Value);
    }

    public void add(){
        result = new Number(n1.getNum() + n2.getNum());
    }

    public String toString(){
        return "" + n1.getNum();
    }

}

Number.java

public class Number {

    private int num;

    public Number() {num = 0;}
    public Number(int numValue){
        if (numValue != 0) num = numValue;
    }

    public Number(Number anotherNum){
        num = anotherNum.getNum();
    }

    public int getNum(){
        return num;
    }

    public void setNum(int numValue){
        if (numValue != 0) num = numValue;
    }   

    public String toString(){
        return new String("" + num);
    }

}
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64

1 Answers1

3

You need to assign values to the class member variables in your constructor of NumberSystem. Currently you are only assigning these values to the local values with the same names which are passed in.

public NumberSystem(Number n1,Number n2){       
    n1 = new Number();  // Number assigned to local variable n1
    n2 = new Number();  // ditto for n2
    ...

This then causes an NPE then you attempt to assign the result on this line:

result = new Number(n1.getNum() + n2.getNum());

Instead you could use:

this.n1 = new Number();
this.n2 = new Number();

or use the values passed in(!?):

this.n1 = n1;
this.n2 = n2;
Reimeus
  • 158,255
  • 15
  • 216
  • 276