【问题标题】:How do you find the first element in array that has a certain characteristic?你如何找到数组中具有特定特征的第一个元素?
【发布时间】:2012-02-12 05:40:23
【问题描述】:

例如,如果您正在搜索一个处理零件的数组,并且您试图找到该数组中具有特定权重的第一个元素。就像权重为 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() {

    }
}

【问题讨论】:

  • 您的问题让人无法理解...请再读一遍并尝试理解...如果您也得到解释...
  • 进一步了解@FahimParkar 的评论 - 您尝试了什么,错误在哪里?

标签: java arrays eclipse


【解决方案1】:

首先...您不能使用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;
}

【讨论】:

    【解决方案2】:
    double searchForLen = 10.00;
    for (int i=0; i < parts.length; i++) {
      if (parts[i].getWeight() == searchForLen) {
        return parts[i];
      }
    }
    

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

    【讨论】:

    • 忽略语法错误的事实,比较 double 这样的值充其量是有问题的。他应该使用BigDecimal 或盎司/克表示为int
    • @FahimParkar 我的代码按要求返回找到的第一部分。 Brian - 语法有什么问题?
    • @alfasin - parts.[i].getWeight() ;那甚至不会编译。这是parts[i].getWeight()
    • 另外......我真的不想在这里竖琴,Double.compare() 与使用== 有同样的问题。请参阅此答案:stackoverflow.com/a/393383/302916。一个丑陋但内容丰富的页面可以在这里找到详细解释:mindprod.com/jgloss/floatingpoint.html
    • @BrianRoach 你说得对,但我认为这有点“矫枉过正”,因为测量体重可能会产生 xx.xx 格式的数字(可以使用双精度数据轻松进行比较type) 所以所有这些讨论都是过时的。
    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多