簡體   English   中英

如何首先更新變量,然后在Java中執行其余代碼

[英]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);
  }
}

所以這是您的代碼將如何執行:

  1. numberOfCups設置為0
  2. priceOfCup設置為5
  3. message已設定
  4. gBetrag已設置
  5. endPreis設置為( numberOfCups * priceOfCup
  6. 當您調用addCups() ,它將顯示endPreis值。

如您所見, endPreis值從未被重新計算過;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM