I need help creating my moneydriver.
requirements:
1- the driver class should create an array of 5 objects.
2- must use loop to determine which Money object has the most amount of money.
3- I need to use compareMoney() method for my comparison.
I start building my MoneyDriver but need help writing the code for the requirements.
Getting: Cannot use this in a static context when the driver is compiled.
MoneyClass:
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;
}
}
MoneyDriver:
import java.util.*;
import java.util.Scanner;
public class MoneyDriver {
public static void main(String[] args) {
final int dollars = 0;
final int cents = 0;
// 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];
// old loop
/** money object in the array
for (int i = 1; i < moneyObject.length; ++i )
if ( moneyObject[i].compareMoney( max ) == 1 )
max = moneyObject[i];
OR BELOW
**/
Scanner scan = new Scanner(System.in);
// new loop
for( int k = 0; k < moneyObject.length; k++ ) {
moneyObject[k] = new Money();
}
this.dollars = dollars;
this.cents = cents;
System.out.println( max );
}
}