你可以在java

时间:2017-03-16 20:39:38

标签: java boolean

我对Java编程比较陌生,我对以下代码有疑问。这是一个名为IntArrayBag的类的一部分:变量data是一个数组实例,变量manyItems是用于保存数组项数的实例。在removeMany方法中,我不明白为什么你可以通过添加remove(target)方法来增加计数。由于remove返回一个布尔值,每次remove方法计算结果为true时计数是否递增?很可能就是这种情况,但我在教科书中找不到任何相关文档。任何澄清都将非常感激。

**编辑下面列出的removeMany方法是我的教科书提供的答案。问题是创建一个可以从数组中删除多个项目的方法,removeMany是教科书提供的答案。这对我来说似乎不合逻辑,这就是我要求澄清的原因。提前谢谢。

public boolean remove(int target)
{ 
    int index;
    index = 0; 
    while ((index < manyItems) && (target != data[index])) 
        index++; 
        if (index == manyItems)
            return false; 
        else { 
            manyItems--; 
            data[index] = data[manyItems]; return true; } 
}

public int removeMany(int... targets) 
{ 
    int count = 0; 
    for (int target : targets) 
        count += remove(target); 
    return count; 
}

1 个答案:

答案 0 :(得分:0)

正如Izruo的评论中所述,转让是非法的。我相信逻辑是每次remove成功时增加计数。但是,remove方法返回的布尔值必须首先更改为int,以便您可以使用它增加count。您可以查看this帖子。

例如,这应该有效:

    public int removeMany(int... targets) 
{ 
    int count = 0; 
    for (int target : targets){
        int removeResult = (remove(target)) ? 1:
        count += removeResult; 
    }
return count; 
}