Перевод Ruby в Java: есть ли в Java конструкция, близкая к оператору переключения Ruby - PullRequest
1 голос
/ 02 ноября 2011

Я пытаюсь перевести то, что у меня есть в 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

Спасибо.

Ответы [ 2 ]

2 голосов
/ 02 ноября 2011

Обновлено:

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

Недостатком является то, что вам придется вручную оптимизировать порядок, в котором они идут.

1 голос
/ 02 ноября 2011

Just:

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

Или сделать каждое условие объектом вашего собственного класса Condition с помощью test () и getMessage () и иметь List.Проблема в параметрах x, y.

...