How to prevent a variable from getting negative in Java?

1

I'm making an Android app in Android Studio where there is a list of items, where you can choose to increase or decrease the amount of each item, so I created two buttons for each item, one to increase and one to decrease quantity, follow template:

int quantity_item;

public void increment_item(View view) {
    quantity_item = quantity_item + 1;
    display_item(quantity_item);

}

public void decrement_item(View view) {
    quantity_item = quantity_item - 1;
    display_item(quantity_item);
}

The problem is that when the value is zero and you click the decrement_item button, the value becomes negative. How do I prevent this? How do I do when I'm in "0", by pressing decrement_item , nothing happens?

    
asked by anonymous 14.09.2017 / 01:35

1 answer

1

Basically create a condition that prevents this:

public void decrement_item(View view) {
    if (quantity_item > 0) {
        quantity_item--;
        display_item(quantity_item);
    }
}

I could also do something like this to get better information:

public void decrementItem(View view) {
    if (quantityItem > 0) {
        quantityItem--;
        displayItem(quantityItem);
    } else {
        messagemErro("Não pode ficar com valor inferior a zero");
    }
}
    
14.09.2017 / 01:38