Jordan Goins
Jordan Goins

Reputation: 17

Update a variable by + or - bassed off what a user enters into a JTextField

I'm trying to make a store counter and want to update the counter based off what user enters in a text field.

I want the counter to change by the number they enter.

So if they enter a 5 it goes up by 5 BUT if they enter a 4 after the 5 the counter goes down by 4.

This is what I have so far but it is only counting up.

int prev = 0;//previus input
int temp = 0;//temp variable
int put = 0;//parsed int
try {
    put = Integer.parseInt(itemCount1.getText());
    if (put < prev) {//if they decrese the number of an item in there cart. 
        temp = put - prev;
        cart.setCartCount(cart.getCartCount() - temp);
        sitem1.setItemCnt(put - sitem1.getItemCnt());
        prev = put;
    }
    if (put > prev) {//if they increse the number of an item in there cart. 
        temp = put - prev;
        cart.setCartCount(cart.getCartCount() + temp);
        sitem1.setItemCnt(put + sitem1.getItemCnt());
        prev = put;
    }
    updateLables(customer);
} catch (NumberFormatException e) {
    storeError.setText("ENTER A NUMBER!!!!");
}

Upvotes: 1

Views: 48

Answers (2)

MarianD
MarianD

Reputation: 14121

In both if statement you have to use + in the expression

cart.getCartCount() + temp

(inside the parentheses of the cart.setCartCount() method),
because in the first if the temp variable has a negative value.

So change the statement

cart.setCartCount(cart.getCartCount() - temp);

to

cart.setCartCount(cart.getCartCount() + temp);     // + instead of -

Upvotes: 1

Austin
Austin

Reputation: 756

if put is less then previous you do

temp = put-prev

since put is less then prev temp will be negative you then do

cart.setCartCount(cart.getCartCount() - temp);

since two negatives make a positive it will add temp instead of subtracting it.

Upvotes: 1

Related Questions