Reputation: 174
I have variables defined outside switch and used them within switch case. I want to run a code that will take value of any switch case. This code will be outside switch. I tried but i got error like STATEMENT UNREACHABLE.
Here what i've tried :
BigDecimal firstvalue, secondvalue, calculation;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
firstvalue = new BigDecimal("45");
secondvalue = new BigDecimal("23");
switch (spinner.getSelectedItemPosition()){
case 0:
{
calculation = firstvalue.multiply(secondvalue);
break;
}
case 1:
{
calculation = firstvalue.add(secondvalue);
break;
}
case 2:
{
calculation = firstvalue.subtract(secondvalue);
break;
}
// Any of above case will apply for calculation
// Then this program that is outside switch should run
calculation.multiply(new BigDecimal("30"));
}
}
});
Upvotes: 0
Views: 917
Reputation: 862
You have written the code line calculation.multiply(new BigDecimal("30")) inside the switch statement itself. So it is part of case 2.
But since you are breaking before the line, that code line is never reached (even for case2). You should really follow indentations as stated in comments to identify such errors easily.
Upvotes: 1
Reputation: 2147
calculation
is assigned inside the switch, but it is defined outside the switch (before the switch starts). This means you can use it after the switch.
All you need to do is move calculation.multiply
one line down, after one of the }
It might be a good thing to assign a default value to calculation, either where it is defined, or using a "default" clause in your switch
Upvotes: 0