Search code examples
javaif-statementswitch-statementslick2d

how do I use switch and case in a java game?


I'm making a game in Slick2D and I have a lot of 'if' statements and I want to get rid of that. Now this is my code:

if((playerPositionX>570 && playerPositionX<835) && (playerPositionY>16 && playerPositionY<260)){
    g.setColor(Color.red);
    g.drawString("Ready to play? press enter!", 400,350);
}

Everything is fine but I have like 8 and going up of these, obviously with different coordinates. So I would like to know if it's possible to use a switch and case method to fix this.


Solution

  • You can't use a Switch with ranges as cases. In other words, something like this:

     Switch(playerPosition)
         case 570-835: 
         ....
    

    doesn't exist. You could do:

    int num;
    
    if (playerPositionX>570 && playerPositionX<835){
        num = 0;
    if (playerPositionX>836 && playerPositionX<1000){
        num = 1;
    

    and then

     Switch(num){
         case 0: 
         ...
         case 1: 
         ...
    

    but you'll still have to use the if statements.