zsoq
zsoq

Reputation: 57

Converting an if-else statement into a switch statement to make code more readable

I need a bit of help converting this code into a switch statement. I'm not used to using switch statements. I am trying to make my code more readable and shorter.

if (move.equals("D")) {
    if ((x + 1) == n) {
        magicSquare[x][y] = magicSquare[0][y];
        magicSquare[0][y] = cache;
    } else {
        magicSquare[x][y] = magicSquare[x + 1][y];
        magicSquare[x + 1][y] = cache;
    }
} else if (move.equals("U")) {
    if ((x - 1) == -1) {
        magicSquare[x][y] = magicSquare[n - 1][y];
        magicSquare[n - 1][y] = cache;
    } else {
        magicSquare[x][y] = magicSquare[x - 1][y];
        magicSquare[x - 1][y] = cache;
    }
} else if (move.equals("R")) {
    if ((y + 1) == n) {
        magicSquare[x][y] = magicSquare[x][0];
        magicSquare[x][0] = cache;
    } else {
        magicSquare[x][y] = magicSquare[x][y + 1];
        magicSquare[x][y + 1] = cache;
    }
} else if (move.equals("L")) {
    if ((y - 1) == -1) {
        magicSquare[x][y] = magicSquare[x][n - 1];
        magicSquare[x][y] = cache;
    } else {
        magicSquare[x][y] = magicSquare[x][y - 1];
        magicSquare[x][y] = cache;
    }
}

Upvotes: 0

Views: 67

Answers (3)

moutasim omran
moutasim omran

Reputation: 23

I encourage you to learn exactly how "switch statement" work and when to use it, programming is all about learning and practicing, getting the answer directly won't help you, here are some references (read and try first)
Stackoverflow Question by zaynv
Great tutorial by codesdope

There are more resources ofc, just read and try simple examples then try on yours. after trying to convert if you face any issues, don't hesitate to post it here.

Upvotes: 2

iamdhavalparmar
iamdhavalparmar

Reputation: 1218

You can use switch() like this.

switch(variable_name){
   case "A":
          //your_work;
          break;
   case "B":
        //your_work;
        break;
   default:
      //always at the end. If you have something which will when the above 
      //options will not work then put it here
}

The values which are going to be checked are characters that's why I put" " if you have integer value you can simply use 1,2,3.... And do not forget to use break at the end of every case else it will run the next case statement.

Upvotes: 0

Stephan Stieger
Stephan Stieger

Reputation: 1

switch(move){
  case "D":
    if ((x + 1) == n) {
        magicSquare[x][y] = magicSquare[0][y];
        magicSquare[0][y] = cache;
    } else {
        magicSquare[x][y] = magicSquare[x + 1][y];
        magicSquare[x + 1][y] = cache;
    }
  break;
  
  case "U":
    Your Code
  break;

  ...
}

You just have to give the switch a value. In the switch you just say for the Case "expected Value" do that and after the Case you make a break

Upvotes: 0

Related Questions