How to prevent a variable from going negative in Java?

Asked

Viewed 667 times

1

I’m making an application for Android in Android Studio where there is a list of items, where you can choose to increase or decrease the amount of each item, so for this I created two buttons for each item, one to increase and the other to decrease the amount, follows model:

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 click on the button decrement_item, the value is negative. How do I stop it? How do I stop it when it’s "0", when pressing decrement_item, nothing happens?

1 answer

2


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 better inform:

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

I put in the Github for future reference.

  • Write like this: código
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; 
 if (quantity_item > 0) { 
 quantity_item--;
 display_item(quantity_item); 
 }

 } However, after increasing the amount, if I try to decrease, in the first click nothing happens, in the second, it decreases two units. What I did wrong?

  • this is related to another issue, what has changed there is just to prevent the number from being negative, nothing else, which was the request in the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.