![](/img/trans.png)
[英]Mapstruct from string to nested object for multiple fields with the same type
[英]Java - Multiple fields of same data type in an object
一堂課后,我正在練習繼承和合成,並決定編寫一個小程序來嘗試一些事情,偶然發現一個問題,我將展示我的代碼,它有4個類,其中包括Main.java:
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Person1", 170); //"Name", height
Person person2 = new Person("Person2", 200); //"Name", height
Bed bed1 = new Bed(160);
Bedroom bedroom1 = new Bedroom(bed1, person1);
bedroom1.sleep();
public class Bedroom {
private Bed theBed;
private Person thePerson;
//Constructors
public void sleep() {
if(thePerson.getHeight() > 180) {
System.out.println("You are too tall to sleep on this bed.");
} else {
theBed.sleepOnBed();
}
}
//Getters
public class Bed {
private Person thePerson;
private int height;
//Constructor
public void sleepOnBed() {
System.out.println("You sleep on the bed.");
}
//Getters
public class Person {
private String name;
private int height;
//Constructor
//Getters
我想要做的是在Main.java的bedroom1
對象中同時使用person1
和person2
,然后在bedroom1
對象上測試sleep()
方法,但我只是想不出一種使用方法。
我嘗試過類似的事情:
public class Bedroom {
private Bed theBed;
private Person thePerson1;
private Person thePerson2;
public Bedroom(Bed theBed, Person thePerson1, Person thePerson2) {
this.theBed = theBed;
this.thePerson1 = thePerson1;
this.thePerson2 = thePerson2;
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Person1", 170);
Person person2 = new Person("Person2", 200);
Bed bed1 = new Bed(160);
Bedroom bedroom1 = new Bedroom(bed1, person1, person2);
bedroom1.sleep();
但是,正如您可能理解的那樣,這不會導致任何結果。 我太累了,無法在線找到任何潛在客戶,可能是因為我使用了錯誤的關鍵字idk。
我希望我的程序采用多個數據類型為Person
對象,並查看它們的高度是否符合在床上睡覺的條件,僅此而已。
您可以在bedroom類中將Person替換為Person對象列表,然后在sleep方法中遍歷數組。
public Bedroom(Bed bed1, List<Person> aListOfPersons)
{
this.persons = aListOfPersons;
}
public void sleep()
{
for(Person aPerson : persons)
{
//check for each aPerson if he fits in the bed
}
}
歡迎使用Stackoverflow,祝您編程愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.