gpt4 book ai didi

java - Mooc Helsinki Part 1 第 4 周练习 18 Java

转载 作者:行者123 更新时间:2023-12-01 14:16:55 27 4
gpt4 key购买 nike

此处描述的程序应在 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类(class):
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 + ")";
}
}

我的解决方案只能打印所有值,而不仅仅是数组中的名字和姓氏:
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);


}


}

我需要修改代码。我是一个初学者,一个解释性的建议将不胜感激。

最佳答案

代替

System.out.println(infoCollection);

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

关于java - Mooc Helsinki Part 1 第 4 周练习 18 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62112331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com