Redbeard Redbeard - 3 months ago 13
Android Question

How to update a variable first and then execute the rest of the code in java

I'm learning app development for Android and have a small problem with my code. In the google tutorial i am working with we created a coffe ordering app. I did some extra coding for my plus and minus buttons, because i wanted them to update the price while changing the amount of cups ordered. That worked great, the moment i press the button the amount of cups and the total price get updated at the same time.

Now here comes my problem. I wanted to output a string with "Total: " + totalPrice, but that doesn't work and i found out why.

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


Here are my global variables:

int numberOfCups = 0;
int priceOfCup = 5;
String message = "Vielen Dank!";
String gBetrag = "Gesamt: ";
String endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);


I ran the code in debugging mode and found out that the method first looks for whats in "gBetrag" and "endPreis" before it updates the "numberOfCups" variable.
The output is "Gesamt: 0.00€" because endPreis is calculated before numberOfCups gets a +1. How do get java to execute the code in the order it was written or rather read the variable after it was updated?

I can workaround this issue if add the variable to every method i want to use it in, but that just adds more code and i tought that's why you use global variables.

Answer

You need to calculate the endPreis each time a cup is added:

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

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