Reputation: 3898
I'm trying to translate what the code I have, in Ruby, to Java.
So far I have been unable to come across a switch statement-type construct in Java that will let me call methods in the cases.
Does anyone have any suggestions for a replacement construct that performs similar to the code below.
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
Thanks.
Upvotes: 1
Views: 225
Reputation: 109567
Just:
if (outOfBound(y, y)) {
message = "...";
} else if (attemptedNonDiagonalMove()) {
message = "...";
} else {
...
}
Or make every condition an object of your own Condition class with a test() and a getMessage() and have a List. Problem are the x, y parameters.
Upvotes: 1
Reputation: 24316
Updated:
if(condition)
{
function();
}
else if( condition)
{
function();
}
Downside is you will have to manually optimize the order in which they go.
Upvotes: 2