gpt4 book ai didi

Java对象: Method doesn't print as it should

转载 作者:行者123 更新时间:2023-12-02 07:18:07 25 4
gpt4 key购买 nike

我有两个类(class):公寓和建筑。公寓等级:

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); 时不起作用?

谢谢您的回答。

最佳答案

在你的

public boolean addApartment(Apartment a) 方法:

this.apartments[this.numOfApartments]=new Apartment(a);

创建一个新公寓,该公寓似乎是由现有公寓 build 而成。这是副本。

提高租金后,

公寓 a=new Apartment(familyName,rent);//构建新的公寓对象。

你传递给

b.addApartment(a)

不会更新租金。这是因为 Java 是按值传递的。它是您的 Building Apartment[] 集合中包含的 new Apartment 中的一个"new"int,即使您从现有公寓中设置它(this.rent = other.rent)

关于Java对象: Method doesn't print as it should,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14663191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com