首页 > 解决方案 > 如何在构造函数被调用后修改其参数?

问题描述

假设我有这个课程:

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);
}
}
}

但是当我打印新的折扣金额时,它保持不变。那么我哪里出错了,我该怎么办?

标签: javaclassinheritancemethods

解决方案


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);
         }
    }

}

推荐阅读