0
public void stackPower(int stackAmount) { super.stackPower(stackAmount); if (this.amount == -1) { this.amount = -2; } else if (this.amount == -2) { this.amount = -3; } if (this.amount == -3) { this.amount = -4; } } 

During testing value goes from -1 to -2 to -4 to -6 etc.

What I want to happen: goes from -1 to -2 to -3 to -4 and then stops.

Could someone explain what I am missing here and how to fix my issue? Thanks.

7
  • 5
    The third one isn't a else-if. Commented Dec 16, 2018 at 2:41
  • 1
    What do you expect to happen? Commented Dec 16, 2018 at 2:41
  • What is the default value in the amount variable? Commented Dec 16, 2018 at 2:42
  • Is the point just to subtract 1 from amount? If so you could just subtract 1 so long as it isn't equal to -4 (assuming that's where you wanted to stop). Commented Dec 16, 2018 at 2:44
  • What is the default value in the amount variable and are you using this in a loop?, if so post the loop block togethe with your question. Commented Dec 16, 2018 at 2:57

3 Answers 3

1

Your third if condition is missing an else (but could just as easily be an else block). Like,

if (this.amount == -1) { this.amount = -2; } else if (this.amount == -2) { this.amount = -3; } else { this.amount = -4; } 

But, I would simplify the logic with a call to Math.max(int, int) like

this.amount = Math.max(-4, this.amount - 1); 
Sign up to request clarification or add additional context in comments.

1 Comment

Hi there, thanks for the reply. I had my code like this prior to changing it to what you see in my post. It doesn't fix the issue completely unfortunately. (it does not exceed -4, but jumps from -2 to -4 still.)
0
 if (this.amount == -1) { this.amount = -2; } else if (this.amount == -2) { this.amount = -3; } 

I think the else if clause will never be executed, because, once the if clause is executed, the else clause wille never be executed.

2 Comments

this way the else if clause does get executed, but any other if (or else if) statement after it will just override it.
int i=1; if(i==1) { i=2; }else if(i==2){ i=3; } System.out.println(i); gives me a 2
0

Simply changing the else if into an if should fix the problem.

The issue you're having is because when you have an if-statement and an else-if, if we go into the if-statement we jump over subsequent else-if statements or else statements.

 public void stackPower(int stackAmount) { super.stackPower(stackAmount); if (this.amount == -1) { this.amount = -2; } if (this.amount == -2) { this.amount = -3; } if (this.amount == -3) { this.amount = -4; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.