![](/img/trans.png)
[英]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.