我在上课后练习继承和写作,决定编写一个小程序来尝试一些事情,偶然发现问题,我会显示我的代码,它有4个类,包括Main.java:< / p>
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中的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
的对象,并查看它们的高度是否符合在床上睡觉的条件,这几乎就是它。
答案 0 :(得分:1)
您可以在卧室类中使用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和快乐编码!