java - 从 Java 中的 ArrayList 中获取 names()
问题描述
我正在尝试两种方法。一个用于添加人员,另一个用于查看他们。这是我到目前为止所得到的:
Contacts contactObj = new Contacts();
private void viewContact() {
System.out.println("Here are your contacts: ");
contactObj.getNames().forEach(System.out::println);
}
private void addContact() {
System.out.println("You're about to add " + firstName + " " + lastName + " to your contacts");
System.out.println("Are you sure? [y]es or [n]o");
String confirmation = fetchContactDetails.next().toLowerCase();
if (confirmation == "y" || confirmation == "yes") {
contactObj.addName(firstName + lastName);
contactObj.addName("connor template");
}
if (confirmation == "n" || confirmation == "no") {
firstName = null;
lastName = null;
}
}
我还有一个看起来像这样的联系人文件:
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Contacts {
private List<String> names;
public Contacts() {
this.names = new ArrayList<>();
}
//add a name to list
public void addName(String name) {
if (!Objects.nonNull(names)) {
this.names = new ArrayList<>();
}
this.names.add(name);
}
//get the name attribute
public List<String> getNames() {
if (!Objects.nonNull(names)) {
this.names = new ArrayList<>();
}
return this.names;
}
}
所以理论上我应该可以调用 addContact() 它应该问我他们的名字和姓氏。然后我应该能够调用 viewContact() 它应该显示人员列表。不幸的是,它显示“这是您的联系人:”,没有联系人。谢谢你的帮助 :)
解决方案
推荐阅读
- c# - 如何重置我的 WPF 动画
- jenkins - Jenkins groovy 如何将测试结果上传到 alm
- javascript - WinJS.UI.ListLayout 使一项内容可编辑,但具有 itemsReorderable
- python - 使用 Telethon 发送 Telegram 消息:某些实体参数有效,其他参数无效?
- groovy - 我们如何在 groovy 中捕获 ManualStepTest 描述和预期结果文本框值
- karate - 如何评论空手道中的多行?
- android - service.startForeground 是否暗示唤醒锁?
- c - 在 C 中解析 tzdata 数据库的工具
- python - 从烧瓶应用程序执行 bash 命令
- git - 我应该避免在私有 git 存储库中使用密钥吗?