Asked by Ashley

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

Answers

Answered by oobleck
I think you forgot a <u>break;</u> statement, so calculation falls through to the next step.
Answered by anonymous
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);
Answered by Ashley
No this was on question paper, So as the previous code is not correct, does it skips to the last step?
There are no AI answers yet. The ability to request AI answers is coming soon!

Related Questions