私はFoodという抽象クラスを持っており、そこでdouble currentCashを59に初期化しています。Foodのサブクラスが2つあります。果物と肉では、59 の現金準備金からユーザーが入力した価格を差し引きます。ユーザーが価格を入力した後、果物または肉の種類に関係なく、次の食品オブジェクトに進みます。現金準備金は再び 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
りんごの種類:マック
Apple の支払い希望価格: 1.0 ドル。
リストには 58.0 ドルが残っています。