与 ArrayList 匹配值?

我对java相当陌生并且已经开始使用ArrayLists并且我被困在一个特定的问题上。


我在下面的代码中试图做的是将一个值传递给方法 locateCatalogue,它将通过数组列表集合来匹配输入的值。


一旦找到匹配的值,停止执行并显示该项目有多少项目。否则,如果数字不存在,只需 return null,这是我的代码:


Arraylist<Catalogue> items;


Public locateCatalogue (int number)

    // if int number matches value entered, find number.

    for(int i=0; i < locateCatalogue.length; i++)

        if (Catalogue.get(i) = number)

            return Catalogue;

        }

        else {

            //return no value if entered value has no matching number.

            return null;

        }


临摹微笑
浏览 166回答 3
3回答

暮色呼如

运算符的=意思是定义变量。供比较使用==。此外,您搞砸了 if 语句:Arraylist<Catalogue> items;Public int locateCatalogue (Catalogue catalogue ){for(int i=0; i < items.size(); i++)if(items.get(i) == catalogue )return i;else&nbsp;return -1;}但是,如果您在找到第一个之后返回,则无法计算您想要的项目。也不清楚你想返回什么

胡子哥哥

public Catalogue locateCatalogue( int number ) {&nbsp; &nbsp;for( Catalogue item : items ) {&nbsp; &nbsp; &nbsp; if( item.id == number ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return item;&nbsp; &nbsp;}&nbsp; &nbsp;return null;}

回首忆惘然

for循环的语法如下:for(int i=0; i < items.size(); i++) {&nbsp; //some code}if 语句的语法是:if(items.get(i) == number) {&nbsp; //some code}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java