java - 如何在构造函数被调用后修改其参数?
问题描述
假设我有这个课程:
public class Customer()
{
private double discountamount;
private double totalPurchase;
public Customer(double tot)
{
this.totalPurchases = tot;
if (tot > 2000.00){setDiscountAmount(0.25);}
else if (tot >= 1000.00){setDiscountAmount(0.15);}
else if (tot >= 500.00){setDiscountAmount(0.10);}
}
public double getDiscountAmount(){return discountAmount;}
public double getTotalPurchases(){return totalPurchases;}
public void setDiscountAmount(double newDiscountAmount){discountAmount = newDiscountAmount;}
public void setTotalPurchases(double newTotalPurchases){totalPurchases = newTotalPurchases;}
}
我想在不创建新对象的情况下更改总购买的价值。
import java.util.Scanner;
public class Discounts
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double totalPurchase;
System.out.print("Enter amount customer has spent: ");
totalPurchase = input.nextDouble();
Customer customer = new Customer(totalPurchase);
System.out.print("\nHas the customer returned with more purchases? ");
boolean loop = input.nextLine().equalsIgnoreCase("yes");
if (loop){
System.out.print("How many times? ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
// Accumulate
System.out.print("Enter amount customer has spent: ");
totalPurchase += input.nextDouble() * customer.discountAmount;
customer.setTotalPurchases(totalPurchase);
}
System.out.println("Customer Discount Amount: " + customer.discountAmount);
System.out.println("Customer Total Purchase Amount: " + customer.totalPurchases);
}
}
}
但是当我打印新的折扣金额时,它保持不变。那么我哪里出错了,我该怎么办?
解决方案
That's because discountAmount
is only set in the constructor, which happens only once an object is instantiated. Instead, you should move the if-statement in your constructor to the setTotalPurchases
, like so:
public class Customer{
private double discountamount;
private double totalPurchase;
public Customer(double tot){
this.setTotalPurchases(tot);
}
public double getDiscountAmount(){return discountAmount;}
public double getTotalPurchases(){return totalPurchases;}
public void setDiscountAmount(double newDiscountAmount){discountAmount = newDiscountAmount;}
public void setTotalPurchases(double newTotalPurchases){
totalPurchases = newTotalPurchases;
if (tot > 2000.00){
setDiscountAmount(0.25);
}else if (tot >= 1000.00){
setDiscountAmount(0.15);
}else if (tot >= 500.00){
setDiscountAmount(0.10);
}
}
}
推荐阅读
- typescript - Bazel 构建错误:预期 build_bazel_rules_typescript 为版本 $
- php - 如何将 php 设置为默认为 curl 请求使用特定的 TLS 版本?
- postgresql - 设置自定义 postgres pid 和日志文件
- c# - 如何在 Xamarin.UiTest 中使用自动化 id 单击元素?
- php - 如何在a中显示父子多维数组
- java - 有什么方法可以关闭后端产生的 MqttClient 线程?
- haskell - 可以在 (& f %~) 和 (^. f) 等运算符来自 Lens 库的情况下应用的函数的类型签名是什么?
- c# - SendGrid 抛出“将内容复制到流时出错”
- tensorflow - 如何防止某些权重的梯度计算
- html - 如何使用 css 和 flexbox 在所选侧导航项的末尾显示箭头?