【问题标题】:Why is my object variable considered null? [duplicate]为什么我的对象变量被认为是空的? [复制]
【发布时间】:2020-05-01 21:12:55
【问题描述】:

在我的方法 answer() 中,它会说我的变量为空。我不明白为什么,因为它指的是具有(最小值,最大值)值的 RandNum 对象。该方法基本上应该根据变量类型返回和、差、商或乘积。它对这两个对象执行此操作,并且应该返回该值。

public class Problem {

private String type;
private int min, max;
private RandNum first, second;


public Problem(String type, int min, int max){
    this.type = type;
    this.min = min;
    this.max = max;
    generateNumbers();
}

private void generateNumbers(){
    RandNum first = new RandNum(min, max);
    RandNum second = new RandNum(min, max);
}

public double answer(){
    if(type.equals("+")){
        return first.getValue() + second.getValue();
    }
    else if(type.equals("-")){
        return first.getValue() - second.getValue();
    }
    else if(type.equals("*")){
        return first.getValue() * second.getValue();
    }
    return first.getValue() / second.getValue();
}

}


public class RandNum {

private int value;

public RandNum(int min, int max)
{
    value = (int)(Math.random()*(max + 1 -min)) + min;
}

public int getValue()
{
    return value;
}
}

【问题讨论】:

  • 您的 generateNumbers 方法将值分配给 局部变量 firstsecond - 您并不是真的想要声明局部变量,而是想要分配值到 字段 firstsecond

标签: java


【解决方案1】:

因为您通过声明同名的局部变量来遮蔽字段,从而立即离开范围。这个,

private void generateNumbers(){
    RandNum first = new RandNum(min, max);
    RandNum second = new RandNum(min, max);
}

应该是

private void generateNumbers(){
    this.first = new RandNum(min, max);
    this.second = new RandNum(min, max);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2021-03-24
    • 2014-03-04
    • 1970-01-01
    • 2014-11-05
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多