java - 使用 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 章是循环/迭代)
这是讲师在不使用 for 循环的情况下使用有关书籍的程序所做的示例。但是,请注意它有 (int index)
作为参数然后使用String title = bookTitles.get(index)
我的观点是,不使用 for 循环我该怎么做?我不希望他们觉得我从互联网上抄袭了我们没有学到的东西。
谢谢,
解决方案
如果您仅限于避免使用for-loop
and 使用if-else
only,则递归调用是一种替代方法:
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
.
推荐阅读
- sql - 仅将 Snowflake SQL 查询中的最后一条语句返回到 R
- css - 部分 Blueprint.css 外观演练在哪里?
- c# - 在不破坏抽象的情况下使日志记录可用的设计模式
- azure - AKS 群集托管标识中的 Nginx 服务无权读取 publicIPAddresses
- c# - 如何向 C# 9 记录添加注释
- python - 无法在 PyCharm 中导入 arcpy
- html - 响应式登录/注册/信息/关于页面未正确调整大小
- reactjs - React 钩子中的状态不会立即改变
- java - Jda discord bot 托管 heroku 问题
- java - Azure Monitor 应用程序启动/停止时间