首页 > 解决方案 > Mooc 赫尔辛基第 1 部分第 4 周练习 18 Java

问题描述

这里描述的程序应该在类 PersonalInformationCollection 中实现。注意!不要修改类 PersonalInformation。

在用户输入最后一组详细信息(他们输入一个空的名字)后,退出重复语句。

然后打印收集到的个人信息,以便每个输入的对象都以以下格式打印:名字和姓氏之间用空格隔开(您不打印识别号)。工作程序示例如下:

Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:

Jean Bartik
Betty Holberton

PersonalInformation班级:

public class PersonalInformation {

    private String firstName;
    private String lastName;
    private String identificationNumber;

    public PersonalInformation(String firstName, String lastName, String identificationNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.identificationNumber = identificationNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getIdentificationNumber() {
        return identificationNumber;
    }

    @Override
    public String toString() {
        return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
    }
}

我的解决方案,我只能打印数组中的所有值,而不仅仅是 Firstnames 和 Lastnames:

public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner scanner = new Scanner(System.in);
        ArrayList<PersonalInformation> infoCollection = new ArrayList<>();


        while (true) {
            System.out.println("First name: ");
            String firstName = scanner.nextLine();
            if (firstName.equals("")) {
                break;
            }
            System.out.println("Last name: ");
            String lastName = scanner.nextLine();
            System.out.println("Identification number: ");
            String identificationNumber = scanner.nextLine();

            infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));


        }
        System.out.println(infoCollection);


    }


}

我需要修改代码。我是初学者,非常感谢您提供解释性建议。

标签: java

解决方案


代替

System.out.println(infoCollection);

你会有

infoCollection.stream().forEach(p -> System.out.println(p.getFirstName() + " " + p.getLastName()));

推荐阅读