gpt4 book ai didi

java - 我的程序中出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 23:56:46 25 4
gpt4 key购买 nike

我正在尝试运行以下程序。然而,NullPointerException正在出现。到目前为止,我已经调试了我的代码的每一步。看来是我实现numA.add()后出现空指针异常的在主要。

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();
}

}

数字.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);
}

}

最佳答案

您需要在 NumberSystem 的构造函数中为类成员变量赋值。目前,您仅将这些值分配给传入的具有相同名称的本地值。

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

这会导致 NPE,然后您尝试在此行上分配结果:

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

您可以使用:

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

或者使用传入的值(!?):

this.n1 = n1;
this.n2 = n2;

关于java - 我的程序中出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com