我在Java中,以下类:它有可能将类定义为双类型java?
public class Percentage
{
private double n;
Percentage (double n)
{
this.n=n;
}
public void setN()
{
this.n=n;
}
public double getN()
{
return n;
}
public double percntage()
{
return this.n/100;
}
}
这个类比例会返回一个双精度值,但问题是,我们不能做任何数学运算与值象下面这样:
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p*12; // this is error because the class Percentage in not of type double
}
有没有办法使百分比类型双?
使用您的getter getN() –
不,'*'可能只对数字类型执行。只需通过调用'p.percntage()'或'p.getN()'(取决于你想要的)来问'p'什么值。由于该方法返回'double',所以在计算中使用它们的结果。 – Pshemo
修正'setN'中的错误代码。 –