我有一個叫做Food的抽象類,其中我將一個double currentCash初始化爲59.我有2個Food類;水果和肉類,其中我從我的現金儲備59中減去用戶輸入的價格。在用戶鍵入價格後,進入下一個食品對象,無論其是水果還是肉類,現金儲備再次返回59 。java hw。具有運行現金儲備的抽象類,現金總是返回初始化的數字
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再一次,不是在價格用戶類型後的新價值。
你是進入
什麼種類的蘋果都
MAC
進入優先
輸入的價格,你願意支付
蘋果的種類:mac
Apple's Price you want to pay:1.0 dollars。
您還有58.0美元可供您購買。
你在哪裏修改'currentCash'的值? – nhgrif
讓我們從簡單的東西開始:你不應該用float或double來代表金錢。使用BigDecimal或int/long。 – Bobby
你在哪裏聲明並賦予'newCash'和'price'值的代碼在哪裏? – nhgrif