[英]Its possible to define class as double type java?
I have the following class in 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;
}
}
this Class Percentage will return a double value, but the problem is we can't make any mathematic operation with values like below: 这个班级百分比将返回一个双精度值,但问题是我们无法使用以下值进行任何数学运算:
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
}
is there someway to make Percentage of type double ? 是否有某种方法可以使类型的百分比增加一倍?
That is an error because you are multiplying the Percentage object with double value. 这是一个错误,因为您正在将Percentage对象乘以double值。 The alternative is 替代方法是
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p.getN()*12;
}
You cannot make the class type double
. 您不能使类类型为double
。 You can perform your operation in the n
value instead. 您可以改为在n
值中执行操作。
b = p.getN()*12;
you can't define a class as double, because double is a primitive type. 您不能将类定义为double,因为double是原始类型。 What you can do is what the others user suggested: 您可以做的是其他用户建议的操作:
p.getN();
It will return the double value you need. 它将返回您需要的双精度值。
No, you can't make it behave like a double
, but (like BigDecimal
) you can supply methods for performing the relevant operations. 不,您不能使其表现为double
,但是(如BigDecimal
)可以提供执行相关操作的方法。
Since your code seems to imply that n = 10
means 10%
, ie a factor of 0.10
, you could make methods like these: 由于您的代码似乎暗示n = 10
表示10%
,即系数为0.10
,因此您可以使用以下方法:
public double of(double value) {
return value * this.n / 100d;
}
public double add(double value) {
return value * (100d + this.n)) / 100d;
}
and then use it like this: 然后像这样使用它:
Percentage p = new Percentage(10);
double input = 55;
double d1 = p.of(input); // 10% of 55 = 5.5
double d2 = p.add(input); // 55 + 10% = 60.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.