将Ruby转换为Java: Java是否有类似于Ruby switch语句的结构?



我正试图把我用Ruby编写的代码翻译成Java。

到目前为止,我还没有在Java中遇到一个switch语句类型的结构,它允许我在这种情况下调用方法。

是否有人有任何建议的替代结构,执行类似于下面的代码。

def move_validator
    message = nil
    case 
    when out_of_bounds?(@x_dest, @y_dest) == true
      message = "You cannot move off the board"
    when no_checker_at_origin? == true
      message = "There is no checker to move in requested location"
    when trying_to_move_opponents_checker? == true 
      message = "You cannot move an opponents checker"  
    when trying_to_move_more_than_one_space_and_not_jumping? == true
      message = "You cannot move more than one space if not jumping"
    when attempted_non_diagonal_move? == true
      message = "You can only move a checker diagonally"
    when attempted_move_to_occupied_square? == true
      message = "You cannot move to an occupied square"
    when non_king_moving_backwards? == true
      message = "A non-king checker cannot move backwards"
    when attempted_jump_of_empty_space? == true  
      message = "You cannot jump an empty space"
    when attempted_jump_of_own_checker? == true
      message = "You cannot jump a checker of your own color"
    when jump_available_and_not_taken? == true
      message = "You must jump if a jump is available"  
    else
      move
      if jumping_move?
        message = "jumping move"
        remove_jumped_checker
      end
      king_checkers_if_necessary
    end
    message
  end

谢谢。

更新:

if(condition)  
{  
   function();  
}  
else if( condition)  
{  
   function();  
}  

缺点是你必须手动优化它们的顺序

Just:

if (outOfBound(y, y)) {
    message = "...";
} else if (attemptedNonDiagonalMove()) {
    message = "...";
} else {
    ...
}

或者用test()和getMessage()使每个条件都成为您自己的condition类的对象,并有一个List。问题是x, y参数

最新更新