0

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"));
               

}
}
});
9
  • What line produces this error? Commented Jul 25, 2020 at 10:54
  • Please edit your question to include the full source code of your java file and add the complete error message you get to your question. Also fix the indentation of your source code so it is easier to see which block starts and ends where. Commented Jul 25, 2020 at 10:54
  • Error is not reproducible, please provide full snippet. Commented Jul 25, 2020 at 10:56
  • This is the complete code. In this code first java will check which option is selected and perform the case accordingly. For example if user selects first option it will run case 0 where it will do multiplication of first and second value and then Calculation variable will be multiplied with 30. Now the error is that calculation.multiply(new BigDecimal("30")); is unreachable statement . ????? Commented Jul 25, 2020 at 10:57
  • Where should i share the complete code ? @Giorgi Tsiklauri Commented Jul 25, 2020 at 11:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.