Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1

Chapter 5 ■ a Java primer: introduCtion to Java ConCepts and prinCiples


case 'D' :
gamePieceDancing(); // Java method controlling Dance sequence if GamePiece is dancing
break;
default :
gamePieceIdle(); // Java method controlling processing if a GamePiece is idle


This switch-case logic construct evaluates the gpState char variable, inside of the evaluation portion of
the switch() statement (notice that this uses a Java method structure), and then provides a case logic block
for each of the game piece states of Walking, Jumping, and Dancing. It also implements a default logic block
for the Idle state. This is the most logical way to set this up because the game piece is usually idle unless it is
that user’s turn.
Since a game piece cannot be Idle, Walking, Running, and Dancing at the same time, I need to use the
break keyword to make each of the branches of this decision tree unique (mutually exclusive) to the other
branches (states).
The switch-case decision-making construct is generally considered to be more efficient and faster than
the if-else decision-making structure, which can use just the if keyword for simple evaluations, which would
look like this:


if(expression == true) {
programming statement one;
programming statement two;
}


You can also add an else keyword to make this decision-making structure evaluate statements that
would need to execute if the boolean variable (true or false condition) evaluates to false rather than true,
which makes this structure more powerful (and useful). This general programming construct would then
look like the following:


if(expression == true) {
programming statement one;
programming statement two;
} else { // Execute this code block if (expression == false)
programming statement one;
programming statement two;
}


You can also nest if-else structures, thereby creating if-{else if }-{else if }-else{} structures. If these
structures get nested too deeply, then you would want to switch, no pun intended, over to using the switch-
case structure. This structure will become more and more efficient, relative to the nested if-case structure,
the deeper your if-else nesting goes. Here’s an example of how the switch-case statement that I coded
earlier for the BoardGame game could translate into a nested if-else decision-making construct in a Java
programming structure:


if(gpState = 'W') {
gamePieceWalking();
} else if(gpState = 'J') {
gamePieceJumping();
} else if(gpState = 'D') {
gamePieceDancing();
} else {
gamePieceIdle();
}

Free download pdf