如何创建一个包含 if 语句的 for 循环? [已关闭]

问题描述 投票:0回答:1

我试图让我的代码只打印 1990 年 1 月 1 日或之后出生的人的姓名。我不知道如何在Java中正确编写if语句条件。这是我的代码:

Person a = new Person("John", LocalDate.parse("1969-03-15"), "+447984356766", "[email protected]");
Person b = new Person("Jane", LocalDate.parse("1998-04-09"), "+447220512328", "[email protected]");
Person c = new Person("Harry", LocalDate.parse("1980-09-25"), "+447220012555", "[email protected]");
Person d = new Person("Anne", LocalDate.parse("1978-01-12"), "+447220012222", "[email protected]");
Person e = new Person("Jack", LocalDate.parse("1996-08-20"), "+447220012098", "[email protected]");

Person[] personArray = new Person[5];
personArray[0] = a;
personArray[1] = b;
personArray[2] = c;
personArray[3] = d;
personArray[4] = e;

LocalDate firstDate = LocalDate.parse("1980-01-01");

for (int i = 0; i < personArray.length; i++) {
  if (getDateOfBirth().isAfter(firstDate)) {
    System.out.println(personArray[i]);
  }
}

我使用了多个 if 语句来打印名称,但已创建数组以使用 for 循环。我只是不知道如何获得正确的代码。

java arrays for-loop if-statement localdate
1个回答
0
投票

我正在尝试让我的代码只打印出生的人的名字 1990 年 1 月 1 日或之后。

使用!

LocalDate#isBefore
而不是
LocalDate#isAfter

此外,您还错过了使用

personArray[i]
。您应该按如下方式更改代码:

if (!personArray[i].getDateOfBirth().isBefore(firstDate)) {
    System.out.println(personArray[i]);
}

Trail:日期时间了解有关现代日期时间 API 的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.