我有一个名为 Food 的抽象类,在其中我将 double currentCash 初始化为 59。我有 Food 的 2 个子类;水果和肉类,我从我的现金储备 59 中减去用户输入的价格。在用户输入价格后,继续处理下一个 Food 对象,无论是水果还是肉类类型,现金储备再次返回到 59 .
abstract public class Food implements Interface {//abstract class.
static public double currentCash=59;
double newCash=0;
}
public class Fruit extends Food implements Interface {
public String name;
public double price;
public String setName;
public int priority;
public Fruit() {
name="no name yet.";
price=0;
priority=0;
realPrice=0;
}
public Fruit(String initialName, int initialPriority, double initalPrice, double initalrealPrice){
name=initialName;
priority=initialPriority;
price=initalPrice;
realPrice=initalrealPrice;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
if (priority > 0 && priority <= 7) {
this.priority = priority;
} else {
System.err.println("Error, enter 1 through 7");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setrealPrice(double realPrice){
this.realPrice=realPrice;
}
@Override
public void writeOutput(){
System.out.println ("Name: "+getName()+" Priority: "+priority +" Price: "+price );
}
public boolean hasSameName (Fruit otherFruit){
return this.name.equalsIgnoreCase(otherFruit.name);
}
public void setPrice(double price) {
this.price=price;
}
public double getPrice(){
return price;
}
public double realPrice(){
return realPrice;
}
@Override
public String eatable() {
String eatablePrint= "Interface eatable";
return eatablePrint;
}
@Override
public void cashReserves() {
newCash= currentCash-price;
if (newCash>0){
System.out.println("You have "+newCash+" dollars left for your list.\n");
}
else
{
String k = "out of cash";
System.out.println(k);
}
currentCash=newCash;
}
@Override
public void realPrices() {
double realCash;
realCash=currentCash-realPrice;// the price you want to pay is what you type in, but the actual price is here.
System.out.println("The grocery store price is " +realPrice+" dollars, and you have "+ realCash+" dollars left.\n");
if (realCash<10){
System.out.println("You're running out of real cash");
}
if (realCash<=0){
System.out.println("You're out of real cash");
}
}
}
在每个 cashReserves 方法之后,currentCash 再次返回 59,而不是用户输入价格后的新值。
你输入的是
什么样的苹果
苹果电脑
输入优先级
1
输入您要支付的价格
1
苹果类型:mac
您要支付的苹果价格:1.0 美元。
您的清单还剩 58.0 美元。