首页 > 解决方案 > 使用 ONLY If 语句在数组中查找元素

问题描述

我之前发表过一篇关于类似主题的文章。但是,我想我会澄清一些事情并改变我的问题。

所以我正在做的这个项目让我很困惑。我只有 5 周的时间,问题是要求我创建一个方法,该方法返回照片数组中的照片标题。每张照片都有一个标题。这是代码:

public class Album {

    private String albumtitle;
    private ArrayList<Photo> photos;

    /**
     * This constructor should initialize the
     * instance variables of the class.
     */
    public Album(String title) {

        this.albumtitle = title;
        photos = new ArrayList<>();

}

/** When passed a title, this method should
     * return the first Photo object in the album with
     * a matching title. If there is no such object, it 
     * should return null.
     * 
     * @param title A title to search for
     * @return A Photo object, or null
     */
    public Photo searchByTitle(String title) {

        //TODO enter code here
        }

    }

现在,我的讲师说不要使用 for 循环,因为该项目是从第 1 章到第 4 章(第 5 章是循环/迭代)

https://lms.uwa.edu.au/bbcswebdav/pid-1134902-dt-content-rid-16529804_1/courses/CITS1001_SEM-2_2018/lectures/BooksReadJournal.java.pdf

这是讲师在不使用 for 循环的情况下使用有关书籍的程序所做的示例。但是,请注意它有 (int index)作为参数然后使用String title = bookTitles.get(index)

我的观点是,不使用 for 循环我该怎么做?我不希望他们觉得我从互联网上抄袭了我们没有学到的东西。

谢谢,

标签: javaarrays

解决方案


如果您仅限于避免使用for-loopand 使用if-elseonly,则递归调用是一种替代方法:

public Photo searchByTitle(String title) {
    return searchByIndex(title, 0); 
}

private Photo searchByIndex(String title, int index) {
    if (index < photos.size()) {                       // Has next? If yes ...
        Photo next = photos.get(index);                //   Get next
        if (!title.equals(next.getPhotoName())) {      //   Does the title match? If not...
            return searchByIndex(title, ++index);      //      Check the next one
        } else return next;                            //   Otherwise you found it
    } return null;                                     // ... if no next, return null
}

我假设Photo该类有一个String photoName可通过 getter 访问的字段,该字段即将与String title.


推荐阅读