英文:
Is there a way to calculate the smallest value from a LocalDate in java?
问题
我正在处理一个Java的作业,其中我有一个Prisoner
类,其中有犯罪日期(dd-MM-yyyy)的LocalDate
格式、姓名和监禁年限。我还有一个Cell
类,我必须在其中将囚犯添加到监狱牢房。
我必须创建一个方法来显示应该首先释放哪个囚犯。
不幸的是,我不知道该如何做。我已经为将囚犯添加到牢房的方法编写了代码,我使用了HashSet,但我不知道如何计算谁应该首先被释放。
以下是我用于添加囚犯的代码:
public Boolean addPrisoner(Prisoner prisoner) {
if (this.prisonerList.size() <= this.cellSize) {
return this.prisonerList.add(prisoner);
}
return false;
}
英文:
I am working on an assignment in java where I have Prisoner
class which have date of offence (dd-MM-yyyy) localDate format, name and years in prison. I also have Cell
class where I have to add prisoners in the cell.
I have to make a method to show which Prisoner
should be release first from the Cell
.
Unfortunately, I have no idea how to do that. I already made a method for adding the prisoners in the cell and I use HashSet but I have not idea how to calculate who should be released first.
This is my code for adding the prisoners
public Boolean addPrisoner(Prisoner prisoner) {
if (this.prisonerList.size() <= this.cellSize) {
return this.prisonerList.add(prisoner);
}
return false;
}
答案1
得分: 0
请参考以下翻译:
让您的囚犯自行计算其释放日期(在现实生活中,这可能会引诱计算欺诈性的释放日期,但只要您编写了该方法,在Java程序中就没问题)。例如:
public class Prisoner {
private LocalDate dateOfOffence;
private int yearsOfSentence;
public LocalDate getReleaseDate() {
return dateOfOffence.plusYears(yearsOfSentence);
}
}
现在,Collections.min
可以找到拥有最早释放日期的囚犯:
Prisoner nextPrisonerToBeReleased = Collections.min(
prisonerList, Comparator.comparing(Prisoner::getReleaseDate));
英文:
Have your prisoner calculate his or her own release date (in real life this might tempt to calculate fraudulent release dates, but as long as you write the method, it’s OK in a Java program). For example:
public class Prisoner {
private LocalDate dateOfOffence;
private int yearsOfSentence;
public LocalDate getReleaseDate() {
return dateOfOffence.plusYears(yearsOfSentence);
}
}
Now Collections.min
can find the prisoner having the earliest release date:
Prisoner nextPrisonerToBeReleased = Collections.min(
prisonerList, Comparator.comparing(Prisoner::getReleaseDate));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论