我有两个课程:公寓和建筑。公寓类:
public class Apartment {
private String familyName;
private int rent;
private boolean isRented;
}
Building 类有一个 Apartment 数组和一个 numOfApartments 变量,它指示该建筑物有多少个公寓,还有一个 FINAL 变量,它指示一栋建筑物中公寓的最大数量。
private Apartment[] apartments;
private int numOfApartments;
private final int MAX_APARTMENTS=20;
public Building() {
this.apartments=new Apartment[MAX_APARTMENTS];
this.numOfApartments=0;
}
现在我想制作一种方法,将公寓的租金提高一个作为参数的金额:
public void raiseRent(int amount) {
for (int i=0; i<numOfApartments; i++) {
apartments[i].setRent(apartments[i].getRent() + amount);
}
}
addAppartment 方法:
public boolean addApartment(Apartment a){ //adds an appartment to the building if
//there's enough space in the array.
if (this.numOfApartments<this.MAX_APARTMENTS)
{
this.apartments[this.numOfApartments]=new Apartment(a);
this.numOfApartments++;
return true;
}
return false;
}
公寓类字符串 ToString 方法:
public String toString()
{
if (this.isRented) //if the apartment is rented, prints:
{
return "Apartment rent: " + this.rent + ". rented to " + this.familyName + " family.";
}
else
return "Apartment rent: " + this.rent + ". not rented yet.";
}
主要是:
String familyName; int rent;
System.out.println("enter family name and rent by this order");
familyName=scan.next();
rent=scan.nextInt();
Apartment a=new Apartment(familyName,rent); //build new apartment object.
Building b=new Building();
System.out.println(b.addApartment(a));
b.raiseRent(200); //initiate the raiseRent method.
这里的一切都有效,但是当我写这个时:
System.out.println(a);
租金显示为旧租金,而不是更新后的租金。当我写这个时:
System.out.println(b.apartments[0]);
有用。
为什么当我写 System.out.println(a); 它不工作?
谢谢你的回答。