2012-02-12 58 views
0

例如,如果您正在通过处理零件的数组进行搜索,并且您试图找到该数组中具有一定权重的第一个元素。如果重量为10,在零件阵列中,第一个元素(部分)的重量为15,第二个元素(部分)的重量为10,则会返回该元素。这些是我用过的方法。我需要制作另一种方法,我想我可能需要调用其中的一种。如何找到具有某种特征的数组中的第一个元素?

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

    } 
} 
+1

你的问题是没有理解......请再次阅读并试着去了解......如果你解释我们太... – 2012-02-12 05:51:29

+0

继@ FahimParkar的评论 - 你尝试过什么和在哪里错误? – Mark 2012-02-12 10:57:22

回答

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

我会采取布赖恩的建议,改变重量的类型。如果你坚持用住你可以使用,然后调用Double.compare()

+0

所以如果你的数据匹配20次,你要返回20次? – 2012-02-12 05:57:30

+0

忽略你的语法错误的事实,比较像这样的double值是最好的。他应该使用'BigDecimal'或盎司/克表示为'int' – 2012-02-12 06:01:34

+0

@FahimParkar我的代码返回找到的第一部分 - 按要求。布赖恩 - 语法有什么问题? – alfasin 2012-02-12 06:14:39

0

首先...你不能使用double和期待的事情,你期望比较。浮点数不准确。您应该使用BigDecimal或更改为使用表示为int的最低公分母(例如盎司或克)来表示您的体重。

之后...遍历数组,直到找到所需重量的匹配。就这么简单。

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; 
} 
相关问题