【发布时间】: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方法将值分配给 局部变量first和second- 您并不是真的想要声明局部变量,而是想要分配值到 字段first和second。
标签: java