Hello,
I'm trying to create a driver for the money class. I need to create and array of 5 money objects. Also I need to use a loop to determine which money object has the most amount of money using "compareMoney()"
class:
public class Money {
private int dollars;
private int cents;
public Money( int dollars, int cents ) {
dollars = dollars;
cents = cents;
adjustMoney();
}
public Money( String m ) {
if( m.charAt(0) == '$' )
dollars = Integer.parseInt( m.substring( 1, m.indexOf('.') ) );
else
dollars = Integer.parseInt( m.substring( 0, m.indexOf('.') ) );
cents = Integer.parseInt( m.substring( m.indexOf('.') + 1 ) );
}
public Money() {
dollars = 0;
cents = 0;
}
private void adjustMoney() {
if( cents >= 100 ) {
dollars++;
cents -= 100;
}
if( cents < 0 ) {
dollars--;
cents += 100;
}
}
// getter methods.
public int getDollars() {
return dollars;
}
public int getCents() {
return cents;
}
// instance methods
public Money addMoney( Money otherMoney ) {
int newd = dollars + otherMoney.getDollars();
int newc = cents + otherMoney.getCents();
return new Money( newd, newc );
}
public Money subtractMoney( Money otherMoney ) {
int newd = dollars - otherMoney.getDollars();
int newc = cents - otherMoney.getCents();
return new Money( newd, newc );
}
public int compareMoney( Money otherMoney ) {
if( dollars > otherMoney.getDollars() )
return 1;
else
if( dollars < otherMoney.getDollars() )
return -1;
else
if( cents > otherMoney.getCents() )
return 1;
else
if( cents < otherMoney.getCents() )
return -1;
else
return 0;
}
public String toString() {
if( cents < 10 )
return "$" + dollars + ".0" + cents;
else
return "$" + dollars + "." + cents;
}
}
Here is my driver:
public class MoneyTester {
public static void main(String[] args) {
// declaring an array of type money with 5 element
Money[] moneyObject = new Money[5];
// initialize
moneyObject[0] = new Money(5,50);
Money max = moneyObject[0];
/** money object in the array
for (int i = 1; i < moneyObject.length; ++i )
if ( moneyObject[i].compareMoney( max ) == 1 )
max = moneyObject[i];
OR BELOW
**/
for( int k=0; k<moneyObject.length; k++ ) {
moneyObject[k] = new Money();
}
Our.dollars = dollars;
Our.cents = cents;
System.out.println( max );
}
}