Jamie West Jamie West - 1 month ago 11
Java Question

Cannot find variable error?

So I am trying to figure out why when I try to edit the boolean equals method so that it has this.dollars == o.dollars it gives me an error code on the second dollars variable in the code and says it cannot find the variable? I know I have a lot of other errors besides this one.

Also, for anyone that is willing to answer, what are the getMoney and setMoney methods there for? Why do I need that instead of just dollars and cents?

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;
}


}

Answer

This is the wrong way around

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.");
    }
}

try

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.");
    }
}

likewise for public void setMoney (int dollars, int cents) {

Regarding equals

In equals the o Object should be tested to see if it is a Money object using instanceof and if so it can then be cast as a Money Object

if( o instanceof Money) {
   return this.dollars == ((Money)o).dollars && this.cents == ((Money)o).cents;  // etc
}