[英]How to update a variable first and then execute the rest of the code in java
我正在學習適用於Android的應用程序開發,我的代碼有一個小問題。 在與我合作的Google教程中,我們創建了一個咖啡訂購應用程序。 我對加號和減號按鈕做了一些額外的編碼,因為我希望它們在更改訂購杯子的數量的同時更新價格。 當我按下按鈕時,杯子的數量和總價格會同時更新,效果很好。
現在是我的問題了。 我想用“ Total:” + totalPrice輸出一個字符串,但這不起作用,我找出了原因。
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
這是我的全局變量:
int numberOfCups = 0;
int priceOfCup = 5;
String message = "Vielen Dank!";
String gBetrag = "Gesamt: ";
String endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
我在調試模式下運行了代碼,發現該方法首先在“ gBetrag”和“ endPreis”中查找內容,然后再更新“ numberOfCups”變量。 輸出為“ Gesamt:0.00€”,因為endPreis是在numberOfCups獲得+1之前計算的。 如何使Java在更新變量后按寫入或讀取變量的順序執行代碼?
如果將變量添加到我要在其中使用的每個方法中,我都可以解決此問題,但這只會添加更多代碼,這就是為什么要使用全局變量的原因。
您需要在每次添加杯子時計算endPreis
:
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
calculateTotal();
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
private void calculateTotal() {
endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
}
我想你的課是這樣寫的:
public class MyClass {
int numberOfCups = 0;
int priceOfCup = 5;
String message = "Vielen Dank!";
String gBetrag = "Gesamt: ";
String endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
}
所以這是您的代碼將如何執行:
numberOfCups
設置為0
priceOfCup
設置為5
message
已設定 gBetrag
已設置 endPreis
設置為( numberOfCups * priceOfCup
) addCups()
,它將顯示endPreis
值。 如您所見, endPreis
值從未被重新計算過;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.