Diego615
Diego615

Reputation: 1

Java finding place in an array?

So I have to find the minimum in an array in Java, but with that I have to print out the corresponding names that go with the minimum in another parallel array. Inside my for loop where I find the minimum, I have a variable place that I set equal to my counter variable from the for loop when the minimum is changed. But every time I print out the name, it prints out the first name in the array instead of the name in the place holder.

public double getMinimum(double[] money)
{
    double lowest = money[0];

    for (int p = 0; p < money.length; p++)
    {
        if (money[p] < lowest)
        {
            lowest = money[p];
            place = p;
        }
    }

    return lowest;
}

Theres the for loop within my programmer-defined class that finds the minimum.

public String getFirstNameMin(String[] firstName)
{
    String minFirstName;          
    minFirstName = firstName[place];          
    return minFirstName;
}

This is the code I'm using to figure out the first name from the first names array at that place. What am I doing wrong? I'm kinda new to Java, but I did all this array stuff in C++ before, so idk if I am missing something very simple, or its different in Java.

Upvotes: 0

Views: 588

Answers (2)

Christian
Christian

Reputation: 1586

Try this:

public int getMinIndex(double[] money)
{
    double min = money[0];
    int minIndex = 0;

    for (int p = 0; p < money.length; p++)
    {
        if (money[p] < min)
        {
            min = money[p];
            minIndex = p;
        }
    }

    return minIndex;
}

public static void main(String[] args)
{
    double[] money;
    String[] name;

    //... init your arrays here!

    int index = getMinIndex(money);

    System.out.println("Min money = " + money[index] + "; name = " + name[index]);
}

However, following an object oriented approach rogues solution is much nicer!!!

Upvotes: 0

Rogue
Rogue

Reputation: 11483

I would say try making a separate class for this that contains the user and the money:

public class User {

    private double money;
    private String fname;
    private String lname;

    //getters/setters/constructors

}

Then from there you can simply compare the accounts:

public User getMinimum(User[] users) {

    if (users.length <= 0) {
        return null;
    }

    User lowest = users[0];
    for (int i = 1; i < users.length; i++) {
        if (users[i].getMoney() < lowest.getMoney()) {
            lowest = users[i];
        }
    }
    return lowest;
}

Upvotes: 1

Related Questions