+ 3
Switch case
IT Seems that i do not exactly understand switch case.
5 Antworten
+ 3
I also use switch statements for things like random moving. Something like this
Random rand = new Random();
int dir = rand.nextInt(5);
switch(dir){
case 1:
xSpeed=1; ySpeed=0;
break;
case 2:
xSpeed=0; ySpeed=1;
break;
case 3:
xSpeed=-1; ySpeed=0;
break;
case 4:
xSpeed=0; ySpeed=-1;
break;
default:
if 1-4 aren't hit, do this one;
break
}
+ 2
break ends it. if I check my dir for example and return 1, it will do what it needs to do and then "break" . basically stop checking the other cases..
in the example with case 1 case 2 case 3, I could also have an extra case which would be default. If dir=5 for example and it checks each case and doesn't hit on one, it will go with the default. .. in the world of switch statements, default == else ..
+ 1
what is your problem with switch?
+ 1
break and default keyword
0
Think of it like checking 1 if statement against lots of possible outcomes. this example checks the big letter and prints the small letter.
string bigLetter="A";
switch(bigLetter){
case "A": System.out.println("a");
break;
case "B": System.out.println("b");
break;
}
Since big_letter is A it will print a.
Here is an example from my own use of it.
https://code.sololearn.com/cpadFEMfJniT/?ref=app