你如何找到具有一定特征的数组中的第一个元素? [英] How do you find the first element in array that has a certain characteristic?

查看:157
本文介绍了你如何找到具有一定特征的数组中的第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果您正在搜索处理零件的数组,并且尝试查找该数组中具有一定权重的第一个元素。像重量一样,在零件阵列中,第一个元件(部件)的重量为15,第二个元件(零件)的重量为10,则会返回该元件。这些是我使用的方法,我需要再做一个方法,我想我可能需要调用其中的一个。

 类Robot {
Part [] parts;
public Robot(){//未显示实现}
public void addPart(PArt p){//未显示实现}
}

class Part {
//类别细节未显示
public double getWeight(){
}
public int get Partnum(){

}
public getMaterial(){

}
}


解决方案

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

我会采取Brian的建议,并更改键入的重量。如果您坚持使用双重,您可以使用双重,然后调用Double.compare()


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()

这篇关于你如何找到具有一定特征的数组中的第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆