java - 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);
}
}
我需要修改代码。我是初学者,非常感谢您提供解释性建议。
解决方案
代替
System.out.println(infoCollection);
你会有
infoCollection.stream().forEach(p -> System.out.println(p.getFirstName() + " " + p.getLastName()));
推荐阅读
- javascript - 使用 React JS 使 Glyphicon 日历图标可点击
- xpages - xp:fileupload 控制和 Chrome 中的部分刷新
- visual-studio - 在 Visual Studio 17 中我的 Selenium Specflow 测试期间变得很刺眼和一些额外的延迟
- git - 如何搜索由掩码给出的文件名的历史记录,并位于任何地方?
- assembly - 指针寄存器可以使用两次吗?
- django - 如何在 django + bootstrap4 中取消没有验证的表单
- python - 点安装。仅创建 dist-info 而不是包
- java - Java 8 高效的 for 循环
- c# - 在 c# 中使用 selenium 进行网页抓取 - 获取 javascript 变量
- reactjs - 我应该创建两个单独的前端 - 桌面和移动吗?