Hadesone 2 Share Posted January 22, 2017 I'm sorta new to java and programming in general, so I learn new things periodically working on random projects(or scripting ;P). I stumbled upon this today when adding a case to my soon to be cow/chicken looter. (I'm currently on my 2nd year of college for web design/software development)So I figured I'd share this info just cause. Hopefully it will help someone out or get someone to use switch statements more often. int i = 1; switch(i){ case 1: String var = "hi"; break; case 2: String var = "yo"; break; case 3: String var = "ayyy"; break; } The previous code won't work because it says that var has already been declared within this scope. So the way to make the scope correspond to each case is to create further nested scopes like this:EDIT: Yes, you don't want to declare a variable in each case. I was just testing some stuff out in my script and copy pasta got me... int i = 1; switch(i){ case 1:{ String var = "hi"; break; } case 2:{ String var = "yo"; break; } case 3:{ String var = "ayyy"; break; } } While I'm at it I guess I'll add on by demonstrating falling through. To show this I'll use a switch that sets how many days in each month: switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numberOfDays = 31; break; case 4: case 6: case 9: case 11: numberOfDays = 30; break; case 2: //for sake of example I didn't include code for leap year numberOfDays = 28; So essentially what this is doing is making multiple cases execute the same line of code.Hope at least someone found these random things useful or interesting. (provided you didn't already know it) . Link to comment Share on other sites More sharing options...
Before 95 Share Posted January 22, 2017 Another way to do it is int i = 1; String var = new String();//or just String var; switch(i){ case 1: var = "hi"; break; case 2: var = "yo"; break; case 3: var = "ayyy"; break; } Something else that's neat: int i = 1; String var = new String();//or just String var; switch(i){ case 1: var = "hi"; break; case 2: var = "yo"; break; case 3: var = "ayyy"; break; default: var = "i wasn't 1, 2 or 3."; break; } Switch statements are incredibly useful for private scripts when mixed with enums. If you haven't discovered those already, they will make your scripting 10x easier, the product 10x better and the updating 10x more manageable. My scripts have become so much better once I figured those out. Link to comment Share on other sites More sharing options...
Scrivus 172 Share Posted January 22, 2017 Another way to do it is int i = 1; String var = new String();//or just String var; switch(i){ case 1: var = "hi"; break; case 2: var = "yo"; break; case 3: var = "ayyy"; break; } I second this, this is just good practice. The way the snippet explains is not at all. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.