创建对象的数学运算符?

时间:2014-03-17 22:17:48

标签: java operators

所以我正在调试我的程序,我必须使用一些运算符。但是,我正在进行比较的值是自定义类的对象。

我创建了这个“Money”类。

public Money(double amount)
{
    if (amount < 0)
    {
        System.out.println(
             "Error: Negative amounts of money are not allowed.");
        System.exit(0);
    }
    else
    {
        long allCents = Math.round(amount*100);
        dollars = allCents/100;
        cents = allCents%100;
    }
}

我有这些错误:

CreditCard.java:55: error: bad operand types for binary operator '<='
     if (balance && amount <= creditLimit)
                           ^
first type:  Money
second type: Money
CreditCard.java:57: error: bad operand types for binary operator '+'
        balance += amount;
                ^
first type:  Money
second type: Money
CreditCard.java:68: error: bad operand types for binary operator '-'
     balance -= amount;
             ^
first type:  Money
second type: Money
3 errors

我正在尝试执行此操作:

public void charge(Money amount)
  {
     if (balance && amount <= creditLimit)
     {
        balance += amount;
     }
     else
     {
        System.out.println("The amount to charge exceeds the credit limit and will not be charged.");
     }

  }

对于使用自定义对象的这类运算符,我该使用什么?

1 个答案:

答案 0 :(得分:2)

在Java中,您不能重载运算符以使用自定义对象。您需要向Money类添加方法以执行所需的操作。例如:

class Money {
    . . .
    public boolean exceeds(Money creditLimit) {
       return dollars > creditLimit.dollars
           || (dollars == creditLimit.dollars && cents > creditLimit.cents);
    }

    public Money incrementBy(Money amount) {
        long allCents = 100 * (dollars + amount.dollars)
            + cents + amount.cents;
        dollars = allCents / 100;
        cents = allCents % 100;
        return this; // for chaining
    }
}
相关问题