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 );
    }
}
        this.dollars = dollars;
        this.cents = cents;

the "this" parts above will give you errors. the compiler is asking for a class instance whose dollar and cents variables will be updated , but this is being called from inside a static method. static methods/blocks are compiled first, everything else comes afterwards. trying to get instance variables updated within a static block/method is like trying to get the egg of a particular chicken before the chicken is even born. in a bit more formal lingo , static stuff cant see non static stuff , instance variables/methods , (as the name suggests) are associated with an "instance" of a class , statics cannot see these things. this is why ur getting a static related error.

the "this" part should be here

    public Money( int dollars, int cents ) {

        dollars = dollars; // this.dollars = dollars;
        cents = cents; // this.cents = cents;
        adjustMoney();
    }

I start building my MoneyDriver but need help writing the code for the requirements.

seeing your compareMoney() code, im assuming you know about java comparators. if not , check them out here(java api) here and and here.

basically , here is what you should be doing :
1. create an arraylist of money objects
2. sort the arraylist based on money using the comparator (compareMoney() in your case) with the collections.sort mechanism in java.
3. get the last element of the sorted arraylist. this will be the one with the largest amount of money.

the other parts of your code might need adustments , but you should first get it up and running , and see the errors (if any).
hope this gets you started.

somjit{},

Thank you, for your input I'm just a beginner on Java would you please take a look at my driver and see if that makes sense thank you again.

Here is my MoneyDriver

import java.util.*;
import java.util.Scanner;

public class MoneyTester {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        final int dollars = 0;
        final int cents = 0;

        // 1- creating 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
        **/


        // new loop
        for( int k = 0; k < moneyObject.length; k++ ) {
            moneyObject[k] = new Money();
            }

        dollars = dollars;
        cents = cents;


        System.out.println( max );
    }
}

i did look at them , i taliked about lines 34,35 of this class itself. see my post above again , perhaps you missed out.

this is a slightly modified version of your money class

class Money implements Comparable<Money> { // comparable is an interface that sorts instances of the class in natural order.

    private int dollars;
    private int cents;
    // new 
    private int value;

    public Money(int dollars, int cents) {

        dollars = dollars;
        cents = cents;
        value = dollars * 100 + 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));
        value = dollars * 100 + cents;
    }

    public Money() {

        dollars = 0;
        cents = 0;
        value = dollars * 100 + cents;
    }

    public int value() {
        return value;
    }

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

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

    // this is the method that does all the comparing. this one in place of your compare money method.
    public int compareTo(Money otherMoney) {

        if (otherMoney.value() > this.value)
            return 1;
        if (otherMoney.value() < this.value)
            return -1;
        else
            return 0;
    }

    public String toString() {

        if (cents < 10)
            return "$" + dollars + ".0" + cents;
        else
            return "$" + dollars + "." + cents;
    }

}

I do not understand quite well...

This part should go into the MoneyDriver?

public Money( int dollars, int cents ) {
dollars = dollars; // this.dollars = dollars;
cents = cents; // this.cents = cents;
adjustMoney();
}

first time i talked about comparators , that was because at first glance , i noticed money being taken in from string. didnt see that the integer.parseInt part , or that it was stored as int. ints make life easy. with int you can simply use a compareTo() method of the comparable interface to sort the moneyObject array out. that is what i incorporated into your money class. then just get the last element , and it will give the one with the biggest money.

this video talks about interfaces , and in particular the comparable one.

a basic example : you have an object array , the compareTo method compares the passed object with the one calling it , if caller is greater the the object passed , returned value is +1 , if the caller is smaller , -1 and 0 if both equal. java's Collections.sort(< your objectList >) will take your list , and sort it by its own using the compareTo method you defined. once that is done, just take the last elements from the list. (you can implement a list using arrayLists. arrayLists are pretty easy , read them here) this element will have the biggest money value you want.

try to write your own code based on what iv said here and the above posts. mistakes makes us learn.

ps : its 2:30 in the morning at my part of the world... time for bed for me. will check this out again tommorow.

Thank you for your time.

also, in one of your first posts in this thread, you had something like:

final int dollars = 0;
...
dollars = dollars;

this is quite ... weird.

first of all, the final keyword won't allow you to change the value of the variable once the value has been set.
secondly..

dollars = dollars;

what would you try to accomplish with that? assiging the value of dollars to dollars? that's a bit redundant, wouldn't you agree?
still, the point holds: unless you want the value of dollars always to be 0, you'll have to remove the final keyword there.

@sultuske : thanks for pointing that out. missed it.
@toldav : you need to treat the finals just as stultuske mentioned , also , instead of keeping dollars and cents and calculating based on them , you can convert it all into cent value , and do all the math stuff based on that. when u have to print something out , just change the cent value to cents n dollars. this will probably save you a lot of code... the adjustMoney() method for one..

the modified code i posted last night , it had a value variable that stored the money as cent value , and this made the code for the compareTo() method a lot easier than the earlier compareMoney() code. see that part , and check it with your original code , should give you an idea of what i mean.

ps:

Thank you for your time

was real sleepy while making the posts last night , perhaps they needed a bit more explanation, do post if there's something troubling you , but yes , also do check out the links i gave you , and try to come up with a rough cut. dosent have to be perfect . :)

Thank you {stultuske,somjit{}},

I cannot get this to work. I fix the change pointed out from you, and I still stuck how the all driver works at the first place. I do understand the first partof the code but I get lost after line 30. I know I have to have the loops in order to process the 5 methods then right after that I'm stuck do not know what to get to process the max or compare.

have you made changes to your code? if so .. post 'em here , code is always better than words :)

here is my last:

public class MoneyDriver {

    public static void main(String[] args) {

        dollars = dollars;
        cents = dollars;

        // creating an array of type money with 5 element
        Money[] moneyObject = new Money[5];

        // initialize
        moneyObject[0] = new Money(5,100);

        Money max = moneyObject[0];

        // loop
        for( int k = 0; k < moneyObject.length; k++ ) {
            moneyObject[k] = new Money();
            }

        //dollars = dollars;
        //cents = cents;
        dollars = max.getDollars();

        System.out.println( max );
    }
}

your doing the same thing as before

        dollars = dollars;
        cents = dollars;

but im not gonna talk about code now, lets move away from the code , lets think of the algorithm , when i dont get my codes to do what i want , iv found that explaining the algorithm to myself , in detail , often with a pen and paper , helps see errors i was jumping over before. try it , and explain in detail steps what you want your code to do.

ill give you a starting hint , related to the error above :

1 > get input from the user;
2 > put the value to the instance of the class

these are the basic stuff you want to do , but you see , your overlooking the "instance of the class" part (for starters) . first create an instance , like

Money greens = new Money(); // green is the reference to this brand new instance of the Money class your giving birth to here
.
// take user input , play with mr.scanner
.
.
greens.setValue(dollars , cents);

this code needs a few things , a refernce , thats the greens thingy , and then the code will take user input and put it into dollars and cents variable of the main method (emphasis on : main method) . these values will be passed to a setter , the setValue(int dollars ,int cents) method of the Money class (there isnt one as of yet , but thats where you the programmer fit in). this setter will set the value of the class variable value (again , this does not exist in your code as of yet , make a dash and write it there), which will be used in all the math stuff to make life easy with simple code. having to work with dollars and cents makes code longer , more complex.

are you with me so far?

can you modify your code to incorporate upto this part?

this is just a simple bare bones code , no comparators , comparables , any of that stuff. simple code that takes in any number of money values , and prints out the biggest one. it should give you some ideas , and help you extend it further if and when you choose to.

import java.util.*;

public class MoneyDriver {
    public static void main(String[] args) {
        Money greens = new Money();
        int biggest = greens.biggest();
        int cents = biggest % 100;
        int dollars = biggest / 100;
        System.out.format("the highest money value entered is : %d:%d cents",
                dollars, cents);
    }
}

class Money {

    private Integer value;
    Scanner is = new Scanner(System.in);
    ArrayList<Integer> valueArray = new ArrayList<Integer>();

    public Money() {
        System.out.println("number of moneyObjects you want to make : ");
        int num = is.nextInt();
        for (int i = 0; i < num; i++) {
            System.out.println("enter dollars and cents : ");
            int dollars = is.nextInt();
            int cents = is.nextInt();
            value = dollars * 100 + cents;
            valueArray.add(value);
        }

    }

    public int biggest() {
        Collections.sort(valueArray);
        return valueArray.get(valueArray.size() - 1);
    }

    public String toString() {
        return String.format("money class last modified with %d entries",
                valueArray.size());

    }

}

somjit{},

I really appreciated your help. I will have some reading and to try to understand the code and see if I can come up with the finall code my self. This is a tremendous help you are giving me.
toldav

no problem :)

let me just talk a bit about objects and comparisons and sorting a bit , since that was a part the problem in your post.

in the original code you posted , you mentioned comparing instances of objects , using comparing methods (your compareMoney method ) but as you see , those are not needed , as you only have one feild to compare : money , which , being an integer ,( and not some abstract stuff like potatoes , eggs , basketball etc etc .. ) makes life easy as java has in built methods for them.

such object comparisons with methods for comparions are required for more abstract data types . an example could be sorting a list of schools based on different parameters at different times. you may want to sort them by the color of their uniforms , to the size of their football feilds to the number of students in each school. so in this case , to compare and sort based on the integer value of student population , you can use a method called compareTo() which is from the comparable() interface . it sorts stuff on natural ordering , which , integer happens to follow. on the other hand , if you want to compare abstact stuff , probably a comparator is a better bet. i did post a link in one of my earlier posts. go through them if you feel these things will be useful to you again.

and reagrding few of the errors you were making ,

        dollars = dollars;
        cents = dollars;

i believe that here you wanted to put the newly obtained values into a particular instance , for that you have to do this :

 classWhoseInstanceYouWantToMake nameOfTheInstance = new classWhoseInstanceYouWantToMake(); // your not doing this part in your main method
 .
 .
 .
 // other code stuff 
 .
 .
 nameOfTheInstance.setterMethod(value_to_set);

 //meanwhile , inside the setter method of the original classWhoseInstanceYouWant(ed)ToMake

 setterMethod(passed_value){
    this.variableName = passed_value ; // note : if variableName and passed value are not same , you dont need the "this" keyword
    // further note : you were doing this inside the main method , but this needs to be done here. call the setter from the main method.

 }

this was perhaps a rant , however i hope it still helps you out in some ways . :P :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.