如何首先更新变量,然后在java中执行其余代码

时间:2016-08-19 20:23:23

标签: java android

我正在为Android学习应用开发,并且我的代码存在一个小问题。在我正在使用的谷歌教程中,我们创建了一个咖啡订购应用程序。我为我的加号和减号按钮做了一些额外的编码,因为我希望他们在更改订购的杯子数量时更新价格。这很有效,我按下按钮时杯子的数量和总价格同时更新。

现在我的问题来了。我想输出一个字符串" 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€"因为在numberOfCups获得+1之前计算endPreis。如何让java按照它编写的顺序执行代码,或者在更新后读取变量?

如果将变量添加到我想要使用的每个方法中,我可以解决这个问题,但这只是添加了更多的代码,我想到了你使用全局变量的原因。

2 个答案:

答案 0 :(得分:1)

每次添加杯子时,您需要计算endPreis

public void addCups(View view) {
    numberOfCups = numberOfCups + 1;
    calculateTotal();
    display(numberOfCups);
    displayMessage(gBetrag + endPreis);
}

private void calculateTotal() {
    endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
}

答案 1 :(得分:1)

我想你的课是这样写的:

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值。
  7. 如您所见,endPreis值从未重新计算过;)