netquoly netquoly - 3 months ago 8
Java Question

How can I do this easy JAVA program?

Person[] people = new Person[] {
new Person("Big", "Joe", 22, 300000),
new Person("Nice", "Peter", 24, 400000),
new Person("White", "Alan", 52, 20000),
};


I'd like to find the name of the person who has the higest money (4. argument). How can I do this easily? Thanks.

I have tried with for and if:

int winner = 0;
for (int i = 0; i < people.length; i++) {
if (i == 0) {
winner = i;
} else {
if (people[i - 1].getCash() < people[i].getCash()) {
winner = i;

}
}
}

Answer

Your if statement is not comparing the right things... Try talking your code out in plain English (or whatever language you speak) and see if it makes sense... You are saying the following:

int winner = 0;                                                   // winner will hold index of person w/most money
     for (int i = 0; i < people.length; i++) {                    // create a loop to go through all People
         if (i == 0) {                                            // is this the first person?
            winner = i;                                           // this IS the first person, so save it as the winner
        } else {                                                  // this is NOT the first person
            if (people[i-1].getCash() < people[i].getCash()) {    // is the cash of the previous person less than the current person?
                winner = i;                                       // the previous person does have less cash than the current person, so save the current person as the winner

            }
        }

This isn't really what you want to do, though, because, say you have it where the people are like this:

person 1 cash = $40,000
person 2 cash = $80,000
person 3 cash = $10,000
person 4 cash = $15,000

the "winner" should be person 2, but using your code it will tell you that the winner is person 4. Why? Because your second if statement will say that person 3 has less cash than person 4 and therefore person 4 is now considered the winner.

Your code would be better to write like this:

int winner = 0;
for (int x = 1; x < people.length; x++) {
    if (people[x].getCash() > people[winner].getCash()) winner = x;
}
// winner now contains the index of the person w/the greatest amount of cash
Comments