首页 > 解决方案 > 从 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() 它应该显示人员列表。不幸的是,它显示“这是您的联系人:”,没有联系人。谢谢你的帮助 :)

标签: javaarraysarraylist

解决方案


推荐阅读