简体   繁体   中英

How do you find the first element in array that has a certain characteristic?

For example if you are searching through an array that deals with parts and you are trying to find the first element in that array that has a certain weight. Like if the weight was 10 and in the parts array the first element(part) had a weight of 15 and the second element(part) had a weight of 10 it would return that element. These are the methods that I used.I need to make another method though and I think I might need to call one of these.

class Robot {
Part[] parts;
    public Robot () { // implementation is not shown }
    public void addPart(PArt p) { // implementation not shown }
}

class Part {
// Class details not shown
    public double getWeight() {
    }
    public int get Partnum() {

    }
    public getMaterial() {

    }
}
double searchForLen = 10.00;
for (int i=0; i < parts.length; i++) {
  if (parts[i].getWeight() == searchForLen) {
    return parts[i];
  }
}

I would take Brian's advice and change the type of the weight. If you insist on staying with double you can use Double and then call Double.compare()

First off ... you can't use a double and expect things to compare as you expect. Floating point numbers are not precise. You should use BigDecimal or change to using the lowest commmon denominator (eg ounces or grams) represented as an int for your weight.

After that ... iterate through the array until you find a match for the weight you're looking for. It's that simple.

public Part findFirst(int weight)
{
    // This will allow us to return null if there's no match
    Part p = null;

    for (int i = 0; i < parts.length; i++)
    {
        // after changing getWeight() to return an int
        if (parts[i].getWeight() == weight)
        {
            p = parts[i];
            break;
        }
    }

    return p;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM