Controlling your program

We'd like to do more than just get input and spit it back out at the user. Here we learn how to analyze the input and respond intelligently.

Booleans and conditions

Booleans

Before we get into responding differently to user input, we have to learn about another another type of variable called a "boolean". A boolean is anything that evaluates to true or false. We can directly assign a value of either true or false to a boolean, or we can do it indirectly by evaluating a condition. We might do a direct assignment to kill one of the units in our game:
boolean unit1IsAlive = false;

Conditions

We might do an indirect assignment to a boolean to determine the current situation in a game. To accomplish this, we will evaluate a condition and assign the result to a boolean. For example, at some point we will need to determine if a particular unit has any moves left because we don't want to allow the user to move a unit if it doesn't have any moves. This assumes that we already have an int variable called unit1Moves which we're using to track the number of moves remaining for a unit.
boolean hasMoves = unit1Moves > 0;
If unit1Moves is any number greater than zero, this condition will evaluate to true, and the value of true will be assigned to the variable hasMoves. Otherwise the value of false will be assigned to hasMoves. The conditional tests we have available to us are ">", ">=" (greater than or equal), "<", "<=" (less than or equal), "==" (equality), "!" (not). Be careful not to confuse "=" (the assignment) with "==" (the equality test). It is a very common programming error to get these two mixed up. The "!" conditional negates the value of the expression that follows it. For example, "! unit1IsAlive" (from above) would evaluate to true because unit1IsAlive was previously set to false;

Complex conditions

This works great for very simple conditions, but very often we have more complex situations that we need to evaluate. What if we wanted to determine if a particular position is a valid position on our 10 x 10 board (we don't have a board yet, but we will soon)? Here's how we would do that using complex expressions. This assumes that we already have two int variables indicating the row and column of the position we want to check.
boolean onBoard = row > 0 
    && row < 11 
    && column > 0 
    && column < 11;
With the complex conditional operator "&&" (meaning "and"), both the left AND the right condition have to evaluate to true for the final value to be true. Otherwise it will evaluate to false. The other complex conditional operator is "||" (meaning "or"). For this operator if either the left OR the right condition (or both) evaluate to true, the final value will be true. Only if both conditions evaluate to false will the final result evaluate to false. You can use parenthesis to group expressions together in the same way as you do in mathematics.

Conditional execution

"if" statements

Now that we know about conditions, we can talk about conditional execution. Thus far in our program the execution of the code has been very straightforward. The program starts on the first line of Stakeout's "main" function and proceeds down to the end of the main function (denoted by the "}" character) executing each line of code on the way. Now I will introduce a feature of the Java language which will complicate this somewhat, but which will give us the ability to respond to the user input. It is called the "if" statement. Here's the general structure:
if (someCondition) {
    someStatement;
    someOtherStatement;
    ...
}
"someCondition" can be any condition. If it evaluates to true, then the statements enclosed in the following brackets will be executed. If "someCondition" evaluates to false or zero, these statements will be skipped. Here's an example that shows the usefulness of this feature. Say that our game allowed 2, 3, or 4 players. In our startup sequence we need prompt the user for how many players he wants to play with and we should only accept the value if it is "2", "3", or "4".
public class Stakeout {

    public static void main (String args[]) throws java.io.IOException {
        System.out.println ("How many players do you want to use? [2, 3, or 4]");
        String input = CmdInput.GetInput ();
        if (input.contentEquals ("2")) {
            System.out.println ("Two players it is!");
        }
        if (input.contentEquals ("3")) {
            System.out.println ("Three players it is!");
        }
        if (input.contentEquals ("4")) {
            System.out.println ("Four players it is!");
        }
        System.out.println ("Game over!");
    }
}
Try to compile this program and then see how it responds to the different input. This code introduces the contentEquals function of the String class. Look at the documentation to familiarize yourself with it. Note that it returns a boolean value. Now the trick comes when we try to respond to an entry other than the 3 valid values that we accept. We will use the System.exit function to immediately quit the program and we will use complex conditionals to detect the situation:
public class Stakeout {

    public static void main (String args[]) throws java.io.IOException {
        System.out.println ("How many players do you want to use? [2, 3, or 4]");
        String input = CmdInput.GetInput ();
        if (input.contentEquals ("2")) {
            System.out.println ("Two players it is!");
        }
        if (input.contentEquals ("3")) {
            System.out.println ("Three players it is!");
        }
        if (input.contentEquals ("4")) {
            System.out.println ("Four players it is!");
        }
        if (! input.contentEquals ("2") 
        && ! input.contentEquals ("3") 
        && ! input.contentEquals ("4")) {
            System.out.println ("You entered an invalid number of players!");
            System.out.println ("Exiting...");
            System.exit (0);
        }
        System.out.println ("Game over!");
    }
}
But this is a little cumbersome, not to mention redundant. There's an easier way...

"else" and "else if" statements

To make this task a easier, the Java language has an "else" statement and an "else if" statement. It can be used to solve our problem above like so:
public class Stakeout {

    public static void main (String args[]) throws java.io.IOException {
        System.out.println ("How many players do you want to use? [2, 3, or 4]");
        String input = CmdInput.GetInput ();
        if (input.contentEquals ("2")) {
            System.out.println ("Two players it is!");
        }
        
else if
(input.contentEquals ("3")) { System.out.println ("Three players it is!"); }
else if
(input.contentEquals ("4")) { System.out.println ("Four players it is!"); }
else
{ System.out.println ("You entered an invalid number of players!"); System.out.println ("Exiting..."); System.exit (0); } System.out.println ("Game over!"); } }
The program will run each line of the main function in order until it reaches the first "if" statement. If the condition evaluates to true, it will execute the statements inside the "if" and then skip the rest of the "else" statements and execute the last println. If the first "if" condition evaluates to false, it will then go on and evaluate the first "else if" statement. If the first "else if" statement evaluates to true it will execute the statements inside and then skip the rest and execute the final prinln. If the first "else if" condition evaluates to false, it will move on to the second "else if" statement. If the second "else if" condition evaluates to true, it will execute the code inside and skip the rest and execute the last println. If the second "else if" condition evaluates to false, it will immediately execute the statements inside the "else" statement (no conditional to evealuate) and then move on and execute the final println. Notice that we no longer need the redundant checks to make sure the input is neither 2, 3, or 4.

A note on indetation: leading whitespace is totally unnecessary. The program above could have been written like this:
public class Stakeout {
    public static void main (String args[]) throws java.io.IOException {
        System.out.println ("How many players do you want to use? [2, 3, or 4]");
        String input = CmdInput.GetInput ();
        if (input.contentEquals ("2")) {
            System.out.println ("Two players it is!");
        }
else if
(input.contentEquals ("3")) { System.out.println ("Three players it is!"); }
else if
(input.contentEquals ("4")) { System.out.println ("Four players it is!"); }
else
{ System.out.println ("You entered an invalid number of players!"); System.out.println ("Exiting..."); System.exit (0); } System.out.println ("Game over!"); } }
In fact the whole program could have been written on a single line, but this would hardly have made it readable. It's important to indent the code inside "if" and "else" statements so that it's easier to follow the flow of execution in the program.

Follow-up exercise

Rewrite your introduction sequence from the last lesson, but use these new features to check for valid input and dynamically respond to the user.


Rate this lesson: *****