这个代码的目的是找到一个人想要购买的商品的数量,这些商品的价格,以及当前的销售情况。对于一个买三送一的免费销售,它看起来像这样
%1个项目为5.0;折扣为0
2件5.0;折扣为0
3件5.0;折扣5.0
4件5.0;折扣5.0
该类扩展了抽象方法为computeDiscount()的抽象类
但是,我不知道如何使这个方法起作用,因为它不会将它作为静态方法排除,但是如果该方法不是静态的,那么我就不能在我的代码中使用它!
我不知道该怎么办,我迫切需要帮助。
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy{
static Scanner input = new Scanner(System.in);
static double itemCost;
static int count = count();
static int n = getN();
static double discount = 0;
public static void main(String[] args) {
itemCost = itemCost();
for(int i = 1; i <= count; i ++) {
discount = computeDiscount(i, itemCost);
System.out.println(i + " items at " + itemCost +
"; discount is " + discount);
}
}
public static double itemCost() {
System.out.print("Enter the cost of the item: ");
itemCost = input.nextDouble();
return itemCost;
}
public static int count() {
System.out.print("How many items are you going to buy: ");
count = input.nextInt();
return count;
}
public static int getN() {
System.out.print("How many items must you buy till you got one free? ");
n = input.nextInt();
return n;
}
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}发布于 2019-10-24 10:27:46
如果您想使用abstraction做任何事情,就不能使用静态方法。在这里,最好结合使用实例变量和工厂方法来执行所有初始化操作。
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy {
// Below are your fields, or instance variables. Notice the lack of static.
final double itemCost;
final int count;
final int n;
public static void main(String[] args) {
// Now you have an instance to work with.
BuyNItemsGetOneFree sale = newInstance();
for(int i = 1; i <= sale.count; i ++) {
double discount = sale.computeDiscount(i, itemCost);
System.out.println(i + " items at " + sale.itemCost +
"; discount is " + discount);
}
}
// Only the factory method can access this.
private BuyNItemsGetOneFree (double itemCost, int count, int n) {
this.itemCost = itemCost;
this.count = count;
this.n = n;
}
public static BuyNItemsGetOneFree newInstance() {
// The scanner really only needs to be used here.
Scanner input = new Scanner(System.in);
// Initilizes itemCost
System.out.print("Enter the cost of the item: ");
double itemCost = input.nextDouble();
// Initilizes count
System.out.print("How many items are you going to buy: ");
int count = input.nextInt();
// Initilizes n
System.out.print("How many items must you buy till you got one free? ");
int n = input.nextInt();
// Constructs and returns
return new BuyNItemsGetOneFree(itemCost, count, n);
}
@Override // Always add this when overriding a method.
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}如果您想更进一步,则不需要computeDiscount中的参数,因为它们(在我看来)只需要引用已经可以使用的字段。
https://stackoverflow.com/questions/58495463
复制相似问题