所以我试图找出为什么当我尝试编辑boolean equals方法以便它有this.dollars == o.dollars它给我一个关于代码中第二个美元变量的错误代码并说它不能找到变量?我知道除了这个之外我还有很多其他错误。
此外,对于任何愿意回答的人来说,getMoney和setMoney方法有哪些?为什么我需要它而不仅仅是美元和美分?
public class Money
{
private int dollars;
private int cents;
private double money;
public Money (int dol) {
this.dollars = dol;
cents = 0;
if (dol < 0) {
throw new IllegalArgumentException ("Must be greater than 0.");
}
}
public Money (int dol, int cent) {
dol = this.dollars;
cent = this.cents;
if (dol < 0 || cent < 0) {
throw new IllegalArgumentException ("Must be greater than 0.");
}
}
public Money (Money other) {
this.dollars = other.dollars;
this.cents = other.cents;
this.money = other.money;
}
public int getDollars () {
return dollars;
}
public int getCents () {
return cents;
}
public void setMoney (int dollars, int cents) {
dollars = this.dollars;
cents = this.cents;
if (dollars < 0 || cents < 0) {
throw new IllegalArgumentException ("Must be greater than 0.");
}
if (cents > 100) {
int c = cents/100;
int m = dollars + c;
}
}
public double getMoney () {
return money;
}
public void add (int dollars) {
if (dollars < 0) {
throw new IllegalArgumentException ("Must be greater than 0.");
}
}
public void add (int dollars, int cents) {
if (dollars < 0 || cents < 0) {
throw new IllegalArgumentException ("Must be greater than 0.");
}
}
public void add (Money other) {
}
public boolean equals (Object o) {
}
public String toString () {
String c = String.format("%.02d",cents);
return "$" + dollars + "." + c;
}
}
答案 0 :(得分:0)
这是错误的解决方法
public Money (int dol, int cent) {
dol = this.dollars;
cent = this.cents;
if (dol < 0 || cent < 0) {
throw new IllegalArgumentException ("Must be greater than 0.");
}
}
试
public Money (int dol, int cent) {
this.dollars = dol;
this.cents = cent;
if (dol < 0 || cent < 0) {
throw new IllegalArgumentException ("Must be greater than 0.");
}
}
同样适用于public void setMoney (int dollars, int cents) {
关于 equals
在equals
o
对象应该使用Money
进行测试以查看它是否为instanceof
对象,如果是,则可以将其转换为Money对象< / p>
if( o instanceof Money) {
return this.dollars == ((Money)o).dollars && this.cents == ((Money)o).cents; // etc
}