Monkeys at Keyboards: APE Antics
© Michael James Heron and Pauline Belford
Topic: Java Programming
Level: 1
Version: alpha

Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.
Albert Einstein

4 - Variety is the Spice of Life

PreviousTable of ContentsNext
Forum


Chapter Objectives

By the end of this chapter, the reader will be able to:



    4.1

    Introduction

    In this chapter we are going to look at the first fundamental building block of programming - the variable. Virtually everything that you do in the future will be based on variables in one form or another - they are easily the single most important tool that you have available to you at this early point in your development career. Their utility may not seem especially high at the moment, but they will soon shine with value as you learn more and more about what Java can do.

    We will also look at a few more of the utility methods available in pacman and how they can be used to obtain information from the person sitting in front of the Pacman game - and how through the medium of variables that information can be sent on to other parts of the program.

    Of a necessity this chapter will not involve us being able to do much more in the way of challenges for APE - think of it as the Rite of Passage you must pass before the rest of the tool bends before your unyielding, uncompromising attacks.

    4.2

    Variables

    As has been indicated before, computers are stupid. They don't do anything that they haven't explicitly been told to do, and more to the point, they don't do things that they haven't been told to do even if those things are inherently sensible. However, computers do have a memory and can hold an awful lot of information in that memory. The downside to this is, again, computers are stupid - they can't look at a number and know it's a number. They need you, a clever person, to tell them what kind of information they have to store.

    There are reasons as to why this is the case (but these reasons are not for us to discuss in this book), but it doesn't make life any easier for a developer. Every specific unit of information that you want to keep for later use must be explicitly stored in the computer's memory, and this is done through the use of things called variables.

    Variables are boxes in the computer's memory, each of which is given a name by which your program can refer to them. Each box has a name, and a type which indicates what the contents of the box are. Your program will have no way of storing information for any length of time without these boxes, and so it is important to make use of them wisely.

    There are many different types for variables, and each type indicates the kind of information that can be contained within the box. To begin with, we are going to look at integers - these are whole numbers (numbers without decimal places) such as 1, 10, -20, 2321 and so on.

    Java uses a shorthand to refer to certain types of variable - in the case of an integer, it uses the shorthand int.

    We declare variables in a Java program using a compact notation - we first give the type of the variable, and then a name by which we can refer to it. For example, to create a box called myNumber that can be used to store whole numbers, we would use the following line of code:

    int myNumber; 

    Note the semi-colon at the end of the line - what we're doing here is telling Java to set aside some memory in the computer, and that space of memory should be big enough to hold a whole number value.

    Traditionally, variables are declared at the start of a method, but they can be declared anywhere within its body. It's good practice those to make sure all your variable are declared in the one place so that you know where to find them and anyone reading your code knows where to find them.

    You have already made use of a variable in your APE programs - all APE programs have at least one variable in them, although it's a little bit more complex than the variables we will be using to begin with. The very first line of code we give to our APE program tells it to create a box that can hold a PacmanGame, and give it the name main. This is a variable declaration.

    If we were to integrate creating an integer variable into a simple APE program, the whole thing would look like the following:

    import draconia.APE.pacman.*; 

    public class VariableMonkey {

    public static void main (String args[]) {
    PacmanGame main = new PacmanGame();
    int myNumber;
    main.setMap ("blank");
    main.showGame();
    }

    }

    Creating the variable is one thing, but we also need to be able to do things with what is contained within the box. We don't know in advance what is going to go in the box - any whole number can be in there. Variables are the programming equivalent of X in an algebra equation... the difference is that we tell the computer what X is going to represent.

    This might seem contradictory: 'We don't know in advance what is going to go in the box' and 'The difference is that we tell the computer what X is going to represent'. At this point, it may be useful to make a distinction between the two key stages in a program's development.

    When you are developing a program in JCreator, it is known as compile-time. When a program is actually executing, it is called run-time. You know completely everything that is happening at compile-time - it's a perfect information game. However, you don't know everything that will happen at run-time, because any time you allow the user to provide their input to the system, you have no way of knowing in advance what they will input.

    We use variables at compile time because they are convenient (and necessary for later kinds of programming structure - more on that later). We use them to deal with user input because they are required - you cannot deal with user input in a dynamic way without being able to store what that input was. We'll see an example of that later in this chapter.

    4.3

    The Assignment operator

    So, the question now becomes - how do we actually make use of these variables? We use them through a series of symbols that are called operators. Some of these will be familiar to you, some will be unfamiliar. Others will look like what you are familiar with, but do something subtly different. That's the joy of programming for you!

    When we first create a variable, it is empty - it contains no information at all. For an integer, this means that it starts off with the value 0 (zero). If we want to change what's stored in the variable, then we use something known as the assignment operator, which takes the form of a single equals sign.

    Now, almost everyone is familiar with what the equals sign means in arithmetic - it means the left hand side is the same as the right hand side. It doesn't mean this in Java though - what it means is make the left hand side equal to the right hand side. In Java terminology again, each side of an operator is known as an operand - so you have the left hand operand and the right hand operand.


    Terminology Alert!

    The assignment operator in Java takes the form of a single equals symbol between two operands. It makes the left hand operand equal to the right hand operand. It does not check to see if the two operands are equal - there is a different operator for that.


    Regardless of what is currently in the left hand side, it changes the value to match what you give it on the right hand side of the operator. For example:

    myNumber = 10; 

    When it is created, myNumber contains the value 0. This line of code is saying 'over-write whatever you have in the myNumber variable currently with the value 10'. myNumber is the left hand operand, and 10 is the right hand operand.

    This only works one way though - you can change the value of variables (that's why they are called variables), but you cannot change the value of real numbers in the same way. The following, for example, would not be a legal Java statement:

    10 = myNumber; 

    We can only work with a variable after it has been created too, so the following is also not valid Java:

    myNumber = 10; 
    int myNumber;

    You can only assign whole numbers to an integer variable. You cannot assign any other kind of number to the variable. If you try and assign a real number (one with decimal places), you will get an error and be unable to compile your program - if you need to store decimal numbers, then you must use a different type of variable, but we'll see that later in this chapter.

    4.4

    So, now what?

    We've given the variable a value, but what do we do now? Well, the big benefit of variables is that they can be used anywhere you would normally use a discreet value. We saw in the last chapter how we can use the sendMessage method to print information out to the display... we could do that instead with a variable. Let's look at a simple program that does that very thing:

    import draconia.APE.pacman.*; 

    public class VariableMonkey {

    public static void main (String args[]) {
    PacmanGame main = new PacmanGame();
    int myNumber;
    main.setMap ("blank");
    main.showGame();
    myNumber = 10;
    main.sendMessage (myNumber);
    }

    }

    Run this simple program and you'll see that it displays the number 10 is the output of the display:

    Sending a Message
    Fig 4.1: Sending a Message

    There is no functional difference between passing a variable as a parameter and passing an actual number. The two give the same result:

    main.sendMessage (10); 

    and

    main.sendMessage (myNumber); 

    The difference comes in how easy it is to manipulate a variable to produce desired output. Variables can have various operations applied to them automatically by Java without you having to do any of the hard work yourself. As programmers, that's what we should be looking for - Java to do all the hard work so that we can spend our days in quiet contemplation of the eternal mysteries of the universe.

    4.5

    Manipulating Variables

    We have available to us a wide range of operators for manipulating variables. The most instantly accessible of these are known as the arithmetic operators and are used to perform basic arithmetic on variables. The list of these is as follows:

    Table of Arithmetic Operators
    Fig 4.2: Table of Arithmetic Operators

    Now, we can try to do some arithmetic on a variable, and all it will tell us is that it can't:

    myNumber / 10; 

    Try to compile this program, and it won't work - because we're telling it to do the arithmetic, but we're not storing the result of it anywhere. We need to store the answer somewhere, which we do in an assignment. Let's create a second integer variable called 'answer' in our program... we then use the assignment operator to assign the result of the arithmetic to a box of its own:

    import draconia.APE.pacman.*; 

    public class VariableMonkey {

    public static void main (String args[]) {
    PacmanGame main = new PacmanGame();
    int myNumber;
    int answer;
    main.setMap ("blank");
    main.showGame();
    myNumber = 10;
    answer = myNumber / 10;
    main.sendMessage (answer);
    }

    }

    All the other arithmetic operators work the same way - we need someplace to store the result, and we need something to perform the arithmetic on. We don't even need to do arithmetic on variables - we can do it on actual numbers in the same way:

    answer = 100 * 1000; 

    We can even chain together arithmetic using the standard arithmetic precedence rules:

    answer = (100 * 100) + 200; 

    For those who maybe don't remember their primary school arithmetic as well as they should, the order of precedence for this is as follows:

    1. Brackets
    2. Orders
    3. Multiplication
    4. Division
    5. Addition
    6. Subtraction

    So for the assignment above, the 100 * 100 will be done first, and then 200 will be added to the result of this.

    4.6

    Variable Voodoo Skills

    All of our examples so far have been using integer variables. There are other types of data provided as standard in Java. These are used in exactly the same way, but are used to store different kinds of data:

    Table of Data Types
    Fig 4.3: Table of Data Types

    Note that each of the different data types need special symbols following an assignment operation. A string needs everything to be enclosed in quotation marks (as we discussed back in chapter one). A char needs things to be enclosed in single apostrophe marks. Other data types need other kinds of symbols which are used by Java to distinguish between, for example, a single character and a string containing a single letter. These distinctions are very important to Java, although they may not seem especially important to you as a developer at the moment.

    Probably the most useful kind of data to be able to work with at this point is time is the String data type, so let's look at how we do that. We start by declaring a variable of type String (note the capital):

    String bing; 

    Then putting a value into it:

    bing = "Hey you guys!"; 

    And then outputting that to the display:

    Main.sendMessage (bing); 

    The full process for this can be seen on the following program listing:

    This gives us the display shown below when we run the program.

    String output with APE
    Fig 4.4: String output with APE

    The question that may be on your mind at the moment is 'Okay, fine - but when do I do all of these things?'. There are some conventions that are followed to ensure that you work correctly with variables. We shall refer to them as The Rules:

    The Rules

    1. Thou shalt declare all thy variables at the start of the method in which they are to be used.
    2. Thou shalt assign values to variables after they have been declared.
    3. Thou shalt perform arithmetic operations on variables after they have been declared.
    4. Thou shalt make use of variables after they have been assigned the correct value.

    The rules are pretty simple, and you'll find as you go through this book that we'll break the first one with wild abandon when we talk about objects and classes - for now though, this is good enough. The first thing you do is declare your variables, and this should be done at the top of the method in which you are going to use the method. It doesn't matter in what order variables are declared - all that matters is that they are declared and you know where to find them.

    You cannot assign values to variables until the variables have been declared, but beyond that there are no rules as to when you manipulate them - you change their value wherever it is appropriate in your program. If you want the value inside the variable to change, then you go ahead and change it by Jingo!

    If you make use of a variable before you assign it a value (for example, if you use it in the sendMessage method) that you will find either that your program doesn't work (such as what happens when you try and do this with a String) or that it gives incorrect input. Before you use the variable, you have to give it the value you want it to have.

    4.7

    Dealing with User Input

    So that's the basics of variables, but we still haven't seen why they are important when dealing with user input. For this, we will have to make use of a set of new methods in our APE program. These are used to get three kinds of user inputs - strings, whole numbers and decimal numbers.

    Each of the methods takes a String parameter, and this String parameter is used to supply text to a simple input box, like so:

    Getting input from the user
    Fig 4.5: Getting input from the user

    In this way we can pull information from the user and make use of it in our program. We invoke this message box with the following line of code:

    main.getTextFromUser ("Enter something funny!"); 

    Consider if we wanted to write a program that took whatever the user entered into this inputbox and then displayed it on APE. We can get the input box up easily enough, but how do we get that into our program?

    There is no way we can know in advance what the user is going to type into this box. If we don't know that in advance, then how can we possibly display what they typed?

    This is where the distinction between compile-time and run-time comes into play. We may not know when we write the program, but we do know once the program has been run and the user has entered the information into the input box. All we need to do is store that information. We want a String of text from the user, and so we setup a String variable:

    String someInput; 

    And then assign that with whatever comes out of the method we provided:

    someInput = main.getTextFromUser ("Enter something funny!"); 

    From this point on, we use our someInput variable exactly the same way as we would use a variable we provided information for ourselves:

    main.sendMessage (someInput); 

    This framework gives us a great degree of power over how the user interacts with our Pacman game. We can provide code, and we also have the power to ask the user to provide information for us. At the moment, we don't know how to do much with the information, but we know how to ask for it.

    If you want a number from the user, then you follow a similar process. The difference is in the type of data that comes out of the method, and the name of the method we use. For whole numbers we use the method getIntFromUser. For decimal numbers, we use getDoubleFromUser. The following program shows all three used in the same program:

    import draconia.APE.pacman.*; 

    public class UserInputMonkey {

    public static void main (String args[]) {
    PacmanGame main = new PacmanGame();
    String someInput;
    int wholeNumber;
    double decimalNumber;
    main.setMap ("blank");
    main.showGame();
    someInput = main.getTextFromUser ("Enter something funny!");
    main.sendMessage (someInput);
    wholeNumber = main.getIntFromUser ("Now enter a whole number!");
    main.sendMessage (wholeNumber);
    decimalNumber = main.getDoubleFromUser ("Now enter a number with ""decimal points!");
    main.sendMessage (decimalNumber);
    }

    }

    4.8

    Some Minor Caveats

    Different data types are used to store different kinds of information, but the kind of information being stored dictates what you can actually do with the data. For example, if you try to multiply a string by any kind of value, it will give you an error. If you try to divide a whole number by zero, it will give you an error.

    On the other hand, trying to add together two strings will give you a concatenated version of the strings. Java will, as far as possible, try to accommodate arithmetic operators on all kinds of data types. It's just unlikely to be able to do it in all cases.

    4.9

    Conclusion

    Variables are the most fundamental of building blocks available in programming languages, and serve as the basis for the majority of the more complex programs as we will see in later chapters. For now they are an oddity, something we need to discuss but they don't open up significant new vistas of power to us. Trust me, they soon will.

    Further Reading

    The following table details further reading on the topic in this chapter, and also any external resources that you may find useful.

    ResourceDescription
    Example Programs from this chapterThis is a zip file of all the programs shown in this chapter.

    PreviousTable of ContentsNext

    © 2004-2006 Michael James Heron and Pauline Belford