【发布时间】:2021-02-02 16:56:03
【问题描述】:
假设我有这个课程:
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);
}
}
}
但是当我打印新的折扣金额时,它保持不变。那么我哪里出错了,我该怎么办?
【问题讨论】:
-
您永远不会更改折扣金额,只会更改总购买金额。
-
我将如何更改折扣金额?如果获取和设置在那里并且我将逻辑从构造函数移动到
setTotalPurchases
标签: java class inheritance methods