[英]How to use binary search in order to find the first element in an array that has certain weight (another element in a different array)?
[英]How do you find the first element in array that has a certain characteristic?
例如,如果您正在搜索处理零件的数组,并且试图在该数组中查找具有一定权重的第一个元素。 就像权重为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() {
}
}
double searchForLen = 10.00;
for (int i=0; i < parts.length; i++) {
if (parts[i].getWeight() == searchForLen) {
return parts[i];
}
}
我会接受Brian的建议并更改重量的类型 。 如果你坚持用双您可以使用双然后调用Double.compare住()
首先,您不能使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.