+ 2
Explain please output of code on Java.
https://code.sololearn.com/c6A2lKxw3dPY/?ref=app I expect output 111. I see it like this: first iteration i=0=x -> Case 0 -> y=100 Second iteration: i=1=x -> Case 1 -> y=110 Third iteration: i=2=x -> case 2 -> y=111 Forth iteration: i=3 -> stop of cycle "For"
5 odpowiedzi
+ 3
Oleg as Ipang pointed out there is no break so if you where to view your code with additional System.out.print() lines you would see the following....
public class Program
{
public static void main(String[] args) {
var x=0;
var y=0;
var i=0;
//the Iterator will go three times 0, 1, 2
for(i=0;i<=2;i++){
x=i;
System.out.println(x);
switch(x){
// as the Iterator goes 3 times the first case 0 will display 100
case 0:
y=100;
System.out.println(y);
// as the Iterator goes 3 times the first case 1 will display 10 + 10
case 1:
y+=10;
System.out.println(y);
// as the Iterator goes 3 times the first case 2 will display 1+1+1
case 2:
y+=1;
System.out.println(y);
}
}
// end result: 123 or 100 + 20 + 3
System.out.println(y);
}
}
+ 2
Oleg , the reason is fall through behavior => the different cases aren't separated with break statement. That's why after a match case, the next cases are also executed.
+ 2
All the switch labels are processed because there is no `break` statement. But which label is processed depends on value of <i>
i = 0, x = 0
y = 100, y += 10, y += 1 => 110
i = 1, x = 1
y += 10, y += 1 => 122
Here `case 0` label skipped cause <x> value is 1.
i = 2, x = 2
y += 1 => 123
Here `case 0` and `case 1` label skipped cause <x> value is 2.
+ 2
Thanks folks. Now I understand the logic. Tomorrow morning I will repeat of "case" syntaxis))
+ 1
Welcome Oleg glad "we" could help