Why is the output of the code 14, not 8 : alpha=3+5=8?
public class Application4{
public static void main(String[] args) {
int alpha=3;
int beta=5;
switch (beta){
case 3:alpha=alpha+3;
case 4:alpha=alpha+4;
case 5:alpha=alpha+5;
default:alpha=alpha+6;
}
System.out.println(alpha);
}
}
3 answers
I think you forgot a break; statement, so calculation falls through to the next step.
you have to put break; after each case like this:
int alpha=3;
int beta=5;
switch (beta){
case 3:alpha=alpha+3;
break;
case 4:alpha=alpha+4;
break;
case 5:alpha=alpha+5;
break;
default:alpha=alpha+6;
break;
}
System.out.println(alpha);
int alpha=3;
int beta=5;
switch (beta){
case 3:alpha=alpha+3;
break;
case 4:alpha=alpha+4;
break;
case 5:alpha=alpha+5;
break;
default:alpha=alpha+6;
break;
}
System.out.println(alpha);
No this was on question paper, So as the previous code is not correct, does it skips to the last step?