gpt4 book ai didi

java - 为什么我添加了构造函数后我的方法不再起作用?

转载 作者:行者123 更新时间:2023-12-02 02:53:50 24 4
gpt4 key购买 nike

我正在观看一个java教程,一旦他将他的类更改为具有构造函数而不是在每个对象中定义每个变量,他的所有方法仍然有效。

我将其更改为构造函数,现在我的方法得到的只是 0。

public class Volume3Lesson4Exercise1 {

public static void main(String[] args) {

groceryStore houstonStore = new groceryStore(534, 0.99, 429, 0.87);
groceryStore seattleStore= new groceryStore(765, 0.86, 842, 0.91);
groceryStore orlandoStore= new groceryStore(402, 0.77, 398, 0.79);

System.out.println("\nSeattle store revenue: ");
seattleStore.calculateGrossRevenue ();

System.out.println("\nOrlando Store Revenue: ");
orlandoStore.calculateGrossRevenue ();

}

}

class groceryStore {
int apples;
double applePrice;
int oranges;
double orangePrice;

groceryStore(int a, double ap, int o, double op){
a= apples;
ap= applePrice;
o= oranges;
op= orangePrice;
}

double calculateGrossRevenue(){
double grossRevenue;

grossRevenue= ((apples * applePrice)+ (oranges * orangePrice));

return grossRevenue;

}
}

在以下代码中,收入返回数字 0 作为总收入。为什么?这些数字仍然与以前相同,但现在只是构造函数而不是每个对象的单独变量。

最佳答案

构造函数中值的分配必须改变顺序,即

groceryStore(int a, double ap, int o, double op) {
apples = a;
applePrice = ap;
oranges = o;
orangePrice = op;
}

这样做意味着传递给构造函数的参数值将保存在实例变量(apples、applePrice 等)中,这是预期的行为。原始代码中显示的赋值没有任何效果,因此实例变量将保留其默认值,即所有数字的 0

为了更清楚起见,this 关键字应该用于所有实例变量,即

groceryStore(int a, double ap, int o, double op) {
this.apples = a;
this.applePrice = ap;
this.oranges = o;
this.orangePrice = op;
}

关于java - 为什么我添加了构造函数后我的方法不再起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43398157/

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