我坚持使用加/减方法来定义一个名为 Money 的类,该类的对象代表美元的金额。该类应该有 2 个 int 类型的实例变量,分别表示美元和美分的金额。包括一个具有 2 个 int 类型参数(表示美元和美分)的构造函数,一个具有 1 个 int 类型构造函数(表示金额为零的美元)和一个无参构造函数。包括用于加法和减法的方法 add 和 minus ,并返回 Money 类型的值。包括一组合理的访问器和修改器方法以及 equals 和 toString 方法。
再次,我陷入了加/减部分,只是无法确定它。另外,等于部分有点令人困惑。是的,这是家庭作业。我正在尽最大努力,但需要一点插入。
请看一下......
public class Money {
private static int dollars;
private static int cents;
public Money()
{
}
public Money(int dollars, int cents)
{
this.dollars = dollars;
this.cents = cents;
}
public Money(int dollars)
{
this.dollars = dollars;
}
public int getDollars() {
return dollars;
}
public void setDollars(int dollars) {
this.dollars = dollars;
}
public int getCents() {
return cents;
}
public void setCents(int cents) {
this.cents = cents;
}
public static Money add(Money m1, Money m2)
{
int cash = m1.dollars + m2.dollars;
int change = m1.cents + m2.cents;
return new Money(dollars, cents);
}
public static int MinusMoney(int m3, int m4)
{
return (m3-m4);
}
public boolean equals(double YourMoney)
{
boolean result;
if (YourMoney > 0)
{
dollars += cents;
result = true;
}
else
{
result = false;
}
return result;
}
public String toString()
{
return ("$" + getDollars() + "." + getCents());
}
public static void main(String[] args)
{
Money MyMoney = new Money(2,30);
System.out.println("You have " + MyMoney.toString());
Money MyMoney1 = new Money(2,30);
Money MyMoney2 = new Money(3,10);
System.out.println("You now have " + Money.add(MyMoney1, MyMoney2));
}
}
最佳答案
要求规定对对象的操作(例如加法和减法)返回一个新实例而不是更改当前实例。因此:
class Money {
private int dollars;
private int cents;
public Money(int dollars, int cents) {
if (dollars < 0 || cents < 0)
throw new IllegalArgumentException("Negative dollars or cents");
this.dollars = dollars;
this.cents = cents;
}
public Money add(Money other) {
int cents = this.cents + other.cents;
return new Money(this.dollars + other.dollars + cents / 100, cents % 100);
}
}
对于equals
,通常会定义它来覆盖Object.equals
,这意味着它需要接受一个Object
而不是一个双
:
public boolean equals(Object other) {
return other != null && other.getClass() == Money.class
&& this.dollars == (Money)other.dollars
&& this.cents == (Money)other.cents;
}
关于java - 定义类名 Money,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35692043/