Learn to Program using Alice

Data Types and Variables

This lesson will teach you about data types and variables.  In addition, the lesson presents and explains two Alice programs.  The first program illustrates the use of local variables for storing data that is completely internal to a function.  The second program illustrates the use of variables for saving input data provided by the user for later use by the program.

Published:  March 30, 2007
Last updated:  May 21, 2007
By Richard G. Baldwin

Alice Programming Notes # 140


Preface

Part of a series

This tutorial lesson is part of a series designed to teach you how to program using the Alice programming environment under the assumption that you have no prior programming knowledge or experience.

Have some fun

Because Alice is an interactive graphic 3D programming environment, it is not only useful for learning how to program, Alice makes learning to program fun.  Therefore, you should be sure to explore the many possibilities for being creative provided by Alice while you are learning to program using these tutorials.  And above all, have fun in the process of learning.

General

In the previous lesson titled "Functions that Return Values" I taught you about functions that return values in Alice.  I taught you how to use existing functions.  I also taught you how to write your own new functions.

In this lesson, I will teach you about data types and variables, and will illustrate those concepts with a pair of working programs.

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

Figures

Listings

Supplementary material

Once you have mastered Alice, I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find a consolidated index at www.DickBaldwin.com.

General background information

Data Types

If you were the manager of the city animal shelter, you probably wouldn't put dogs and cats into the same pens.  Dogs and cats are not only different types of animals, they also happen to be different types that don't co-exist very well in the same confined quarters.

Think of data as dogs, cats, bears, etc.

The same concepts apply to data in a computer program.  Data comes in a variety of different types that don't co-exist well in the same space.  For example, Java recognizes eight different primitive data types as well as numerous abstract types.  While Alice doesn't categorize data into that many different types, it does categorize data into the following types:

Four types are somewhat general purpose

Of the fifteen types listed above, the following four types are somewhat general purpose types and the remainder are more specialized types.

 
The Transformable type
When I inquired about this type I was told:

"Transformable is an internal data type that is not intended to be
directly manipulated by end users. If you have managed to see the word
'transformable,' that probably indicates that you've gotten the system to cough up some internal information."

Bottom line, just ignore the Transformable data type.  Apparently you can't use it.

I will explain these four types in some detail in this lesson.  You will learn about the specialized types on an as-needed basis during the remaining tutorial lessons in this series.

Type Number

Probably the most significant distinguishing characteristic of data of the type Number is that you can perform arithmetic using that data.  Several examples of data of the type Number follow:

Java subdivides the general numeric type into six different types, some of which are whole (integer) values, and some of which are allowed to have fractional parts.  The main differences among these different numeric types have to do with the accuracy of arithmetic that can be performed using the different numeric types.  However, to make life easier for you, Alice treats all numeric types as the single type Number.

Type Boolean

This is probably the simplest of all types in that data of this type can only have one of two different values: true or false.

Data of the Boolean type originates primarily as a result of tests that compare one thing with another such as:

You will learn a great deal more about data of type Boolean in future lessons that address selection and loop structures along with relational operators.

Type Object

Data of type Object contains references to objects on which you call methods and functions, such as:

You can create variables of the Object type and save references to such objects in those variables.

Creating a new type
If you right-click on an object in the object tree, you will see an item labeled save object... in the popup menu.  In effect, this makes it possible for you to create a new class that extends the class from which the original object was created.  Creating a new class also results in the creation of a new type.  However, this is a rather complex topic, which will be deferred until a future lesson that deals with saving and importing objects.

Type String

Along with type Number, this is probably the most commonly used type of all.  Typically, data of type String contains what might be thought of as a label in the non-technical world.  For example, you could use a variable of type String to store your name or your telephone number.

I mention your telephone number for a very special reason.  If you store a telephone number as type String, you cannot perform arithmetic using that data even if it consists solely of the digits from 0 through 9 inclusive.  You can only perform arithmetic using data of type Number.

Can only store data in compatible types

Every local variable is identified as belonging to a specific type.  This means that the memory that has been set aside to be used as a variable can only be used to store a specific type of data.

That sums it up

That pretty well sums up the topic of data types.  Not all programming languages require data to be categorized into different types, but Alice is one of the programming languages that does have that requirement.  However, particularly with respect to the Number type, Alice is somewhat less demanding than other languages such as Java, C++, and C#.

Variables

Some people throw all of their clothes in a big pile on a shelf in their closet.  That is analogous to programming languages that don't deal with data types.  Hopefully the meaning of this sentence will become clear as you read the following paragraphs.

Other people are careful to hang each item of clothing on its own hanger.  If you are one of those people and you are really fastidious, you will have different types of hangers for the different items of clothing.

A special type of hanger for trousers

For example, trousers will probably be hung on hangers of a type that prevents horizontal creases from forming at about the knee-level on the trouser legs.  (The cheap version of this type of hanger is an ordinary wire hanger with a cardboard roll on it.)

Special hangers for suit coats and shirts

The hangers for suit coats may be made of material that is thicker than an ordinary wire hanger and slightly curved forward under the shoulder pads of the suit coat.  This will prevent damage to the shoulder pads.

Shirts may be hung on simple wire hangers such as those that seem to originate at the commercial laundry, or they may be hung on more decorative plastic hangers.

Variables are similar to hangers

Variables in Alice are similar to hangers in a closet.  A variable is a place in memory where data of a specific type can be stored for later retrieval and use.  The hangers in a closet provide a place where clothing items of different types can be stored for later retrieval.  However, unlike the hangers in a closet, each variable is given a unique name to make it easy to find in order to store and retrieve data into it.  (The hangers in my closet don't have unique names.)

Local variables, instance variables, and properties
Variables that exist inside methods or functions are often called local variables in other programming environments.

Variables that exist inside an object but outside of a method or function are often called instance variables in other programming environments.  However, they are called properties in Alice.

The locations of variables

In Alice, variables can exist in at least two different locations in a program:

One of the primary differences between the two different locations has to do with the lifetime of the variable.

The lifetime of local variables

When a method or function is called, control passes to that method or function.  The local variables belonging to that method or function come into existence at that point.  They can be used while control remains in the method or function.  However, they cease to exist and become unavailable for use when control returns from the method or function to the method or function that performed the call.  Therefore, local variables can't be used to carry data forward from one method call to the next call to the same method.

The lifetime of object variables (properties)

In Alice, variables that belong to objects are called properties.  They come into existence when the object is created, and they cease to exist when the object ceases to exist.  As a practical matter, objects cannot be created or destroyed in Alice while a program is running, so properties belonging to an object exist during the entire running time of the program.

Just like local variables, every property is identified as belonging to a specific type.

Preview

In this lesson, I have begun by teaching you about data types and variables.  Next, I will present and explain two Alice programs.  The first program will illustrate the use of local variables for storing data that is completely internal to a function.  The second program will illustrate the use of variables for saving input data provided by the user for later use by the program (data obtained from an external source).

I will not illustrate property variables in this lesson, but I will explain how to declare and initialize them.  Once they have been declared, except for the fact that they have a much longer lifetime, the procedures for using property variables is pretty much the same as the procedures for using local variables.

Discussion and sample code

The program named Alice0140a

This program is an upgraded version of the program named Alice0135a that I developed and explained in the earlier lesson titled "Learn to Program using Alice, Functions that return values" (see Resources).

Coach displayed width in a comic-strip bubble

As you may recall, that program constructed and executed a call to the say method to cause a coach object to display his width in a comic-strip bubble above his head.  Both the construction of the statement and the explanation of that construction were very complicated.  At that time, I told you that the code in that program could be simplified (made less cryptic) through the use of local variables.  However, since we hadn't studied local variables at that point, I was unable to use them.

The time has come to simplify that code using variables

Well, now we have studied, or at least are currently studying local variables, so it is time to show you how to use local variables to simplify the code in that earlier program.

Procedure for writing the program

The easiest way to write the program named Alice0140a is to load the earlier program named Alice0135a into your Alice development environment, save it as Alice0140a, and then edit the code to produce the desired behavior for the upgraded version.

Screen shots from the program

Four screen shots from the upgraded version of the program are shown in Figures 1 through 4.  Figure 1 shows the screen output from the early part of the program that uses the code from the earlier version of the program to get and to display the coach's width.  This code doesn't use variables, and is presented simply to serve as a baseline against which to compare the upgraded code.

Figure 1. Coach reporting width without variables in program Alice0140a.

Do a little dance

Figure 2 shows the coach doing a little dance (he turns one revolution) to signal the transition of the program from the old code that doesn't use variables to the upgraded code that does use variables.

Figure 2. Coach doing a little dance in program Alice0140a.

Results from code that uses variables

Figure 3 shows the screen output for the upgraded code that uses variables to get and display the coach's width.  Let me emphasize at this point that the results are the same.  Neither approach is either right or wrong as compared to the other approach.  However, the code that uses variables is considerably less cryptic and should be easier to understand than the code that doesn't use variables.

Figure 3. Coach reporting width using variables in program Alice0140a.

More output from code that uses variables

Figure 4 shows the screen output for the upgraded code that uses variables to get and display the coach's width after he raises his arms, thereby making his bounding box narrower.

Figure 4. Coach reporting width using variables in program Alice0140a.

Source code for the program named Alice0140a

The source code for this program is presented in Listing 1 near the end of the lesson.  An executable version of the program is also available for downloading (see Resources).

The first call to the say method on the coach object shown in Listing 1 was copied from the earlier version of the program named Alice0135a.  I explained the construction of this statement in the earlier lesson titled "Learn to Program using Alice, Functions that return values" (see Resources) so I won't repeat that explanation in this lesson.  I included that statement in this program simply for comparison with the new version of the code.

Interesting new code

The interesting new code occurs at the very beginning of the main method (variable declarations) and further down beginning at the comment that reads "Coach reports his current width using variables."

Declaring and initializing variables

Figure 5 shows a partial screen shot of the edit pane during the development of the program named Alice0140a.

Figure 5. Screen shot of edit pane for program Alice0140a.

Creating a new property variable
Use the same procedure for creating a new property variable, except click the button with the same label on the properties tab below the object tree after selecting an object in the object tree.

Procedure for creating a new local variable

The procedure for creating (more properly called declaring) and initializing a new local variable is to click the button labeled create new variable shown in the upper-right corner of Figure 5.  This causes the dialog shown in Figure 6 to appear on the screen.

Figure 6. Dialog for declaring and initializing a new local variable.

Create and initialize the new variable

To create and initialize the new variable:

Variables used in this program

Once you complete those four steps, the type, the name, and the specified initial value of the new variable will appear at the top of the program code as shown in Figure 5, which shows four variables having the following names:

The purpose of each of the four variables is also briefly described in the above list.

Procedure for using local variables in program code

Whenever you need to use a local variable in your program code, you drag it down and drop it at the appropriate location in the program code.

If you drop the variable on a new line all by itself, the skeleton of a new statement such as the statement that begins with "coachesWords.set..." in Listing 1 will be created automatically.  You then use the normal Alice drag and drop paradigm to complete the statement.

If you need to insert the variable in an existing skeleton of a statement, you use the normal Alice drag and drop paradigm to drag the variable and drop it on top of a placeholder that already exists in that skeleton statement.  (See the statement in Listing 1 that contains "coachesWidth.toString()" for example.)

Description of the program code

The doInOrder block of code following the comment that reads "Coach reports his current width using variables" in Listing 1 contains four statements that set the values of the four variables.  These relatively simple statements were constructed using the normal Alice drag and drop paradigm.  The last such statement, when executed, results in the variable named extendedString containing a string that is the concatenation of the contents of the variable named coachesWords and the string that results from:

The contents of the variable named extendedString are then passed to the method named say, which is called on the coach object to produce the screen output shown in Figure 3.

Behavior of the remainder of the program

The remaining code in the program does essentially the same thing again after causing the coach object to lift both arms skyward, thereby causing the bounding box containing the coach object to become narrower.  This produces the screen output shown in Figure 4.

The program named Alice0140b

If you examine Listing 1 carefully, you will find a statement that instructs the coach object to turn RIGHT by 1 revolution in the default duration time of one second.  The program named Alice0140b upgrades this program to allow the user to specify the number of revolutions that the coach object should turn at that point in the program.  As such, the changes that were required to the program named Alice0140a to produce the program named Alice0140b were very modest.

Source code for the program named Alice0140b

The source code for this program is presented in Listing 2.  You can also download an executable version of this program (see Resources).  The first thing to notice in Listing 2 is the addition of a new variable of type Number named numberRevs with an initial value of 5.  (In this program, the initial value is of no consequence and might just as well have been left at the default value of zero.)

Get the number of revolutions from the user

The second thing to notice in Listing 2 is the call to the world's function named NumberDialog very near the beginning of the program.  This results in the dialog shown in Figure 7 being displayed on the screen for the purpose of soliciting numeric input from the user.  (The world object also provides similar functions for soliciting Boolean and String input from the user.)

Figure 7. Numeric user input dialog.

A modal dialog

This is a so-called modal dialog, meaning that it won't go away and the program won't continue running until the user clicks the OK button.  Some programming languages provide non-modal dialogs that can remain on the screen while the program continues to run, but I don't believe that non-modal dialogs are provided by Alice.

If the user enters a non-numeric value in the text field in Figure 7 and clicks the OK button, the program will fail with a runtime error.  When the user enters a numeric value in the text field and clicks the OK button, the value entered by the user is returned by the function named NumberDialog in Listing 2, and the returned value is stored in the variable named numberRevs.

Using the user-input value

The third thing that to notice about the code in Listing 2 is the modification of the call to the turn method so as to use the value stored in the variable named numberRevs to specify how many revolutions the coach object is to turn when he does his little dance.  Thus, user input data is used to control this aspect of the behavior of the program.

Otherwise no different

Beyond that, there are no differences between the program named Alice0140b and the earlier program named Alice0140a.  Except for the number of revolutions turned by the coach, the screen output for the two programs is the same.  Since I am unable to capture that difference in a screen shot, I didn't provide any screen shots for this program.

Run the programs

Executable versions of the programs that I explained in this lesson are available for downloading (see Resources).  I encourage you to either download those programs, or copy the code from Listings 1 and 2 into your Alice development environment and play the world.  Experiment with the code, making changes, and observing the results of your changes.

Summary

In this lesson, I provided an explanation of data types and variables.  Then I presented and explained two Alice programs.  The first program illustrates the use of local variables for storing data that is strictly internal to a function.  The second program illustrates the use of variables for saving input data provided by the user for later use by the program.

I did not illustrate property variables in this lesson, but I did explain how to declare and initialize them.  Once they have been declared, except for the fact that they have a much longer lifetime, the procedures for using property variables is pretty much the same as the procedures for using local variables.

What's next?

As of this writing, I am planning to teach you how to write and use world-level methods, both with and without parameters in the next lesson.

Lab project

Create a new world using the grass template.  Place a Coach object in the world.

Rename the default method main.  The method named main must be empty except for comments and a call to a world-level method named processData.

Write the code in the method named processData to do the following:

Figure 8. Input dialog for coach's name.

 

Figure 9. Program output for coach's name.

 

Figure 10. Input dialog for coach's age.

 

Figure 11. Program output for coach's age.

Save your world in a file named Alice140LabProjA.a2w and be prepared to deliver it to your instructor in whatever manner the instructor specifies.

Make certain that your preferences are set to Java Style in Color.

Select Export Code For Printing... on the File menu and save your source code in a file named Alice140LabProjA.html.  Also be prepared to deliver this file to your instructor in whatever manner the instructor specifies.

View a movie of the lab project

You can download and play a small, low-quality movie of my version of the lab project as it being executed from the Resume button (see Resources).  This movie was designed to give you a rough idea of how your program should behave.  The movie was purposely recorded in low-quality wmv format in a small window in order to reduce the file size and hence reduce the download time.

Because of the low quality of the movie, the execution of your program should provide much smoother animation than the movie, and should be much less grainy than the movie.  Also, because of the low quality of the movie, the timing in the movie doesn't necessarily match the duration times specified for the lab project.

I attempted to synchronize the beginning of the recording with the beginning of the program execution by starting, then quickly pausing, and then resuming the execution.  If you watch closely, when the movie starts running, you will see the mouse pointer click the Resume button, and the movie will show one complete pass through the program.

You should view this movie in its original size.  If you allow the media player to enlarge it, the quality will be poor.

Resources

General resources

Resources from earlier lessons in the series titled "Learn to Program using Alice"

Downloads

Complete program listings

Complete listings of the programs discussed in this lesson are presented in Listings 1 and 2 below.

Listing 1. Source code for program named Alice0140a.

Alice0140a's Code

Created by: Dick Baldwin

world

Methods

  public void main ( ) {
    String coachesWords = My width is ; Number coachesWidth = 0 ; String widthAsString = default string ; String extendedString = default string ;
       // Copyright 2007 R.G.Baldwin
  // Program demonstrates the use of variables.
  doInOrder {
       // Coach reports his current width without using variables
  // and turns once.
  doInOrder { . . . }
       // Statement taken from program Alice0135a.
  coach .say( ( My width is + ( ( subject = coach .getWidth() ) .toString() ) ) ); duration = 3 seconds
  coach .turn( RIGHT , 1 revolution );
  }
  // Coach reports his current width using variables.
  doInOrder { . . . . . }
       coachesWords .set( value , My width is still );
  coachesWidth .set( value , ( subject = coach .getWidth() ) ); duration = 0 seconds
  widthAsString .set( value , ( coachesWidth .toString() ) ); duration = 0 seconds
  extendedString .set( value , ( coachesWords + widthAsString ) ); duration = 0 seconds
  coach .say( extendedString ); duration = 3 seconds
  }
  // Coach raises both arms and reports new width.
  doInOrder { . . }
       doTogether { . . }
       coach.upperBody.leftArm .roll( RIGHT , 0.25 revolutions );
  coach.upperBody.rightArm .roll( LEFT , 0.25 revolutions );
  }
  doInOrder { . . . . . }
       coachesWords .set( value , Now my new width is );
  coachesWidth .set( value , ( subject = coach .getWidth() ) ); duration = 0 seconds
  widthAsString .set( value , ( coachesWidth .toString() ) ); duration = 0 seconds
  extendedString .set( value , ( coachesWords + widthAsString ) ); duration = 0 seconds
  coach .say( extendedString ); duration = 3 seconds
  }
  }
  }
  }

 

Listing 2. Source code for the program named Alice0140b.

Alice0140b's Code

Created by: Dick Baldwin

world

Methods

  public void main ( ) {
    String coachesWords = My width is ; Number coachesWidth = 0 ; String widthAsString = default string ; String extendedString = default string ; Number numberRevs = 5 ;
       // Copyright 2007 R.G.Baldwin
  // Program demonstrates the use of variables.
  // Also demonstrates user input.
  doInOrder {
       // Get number revs from user.
  numberRevs .set( value , ( NumberDialog( question = Enter number revolutions for coach ) ) );
  // Coach reports his current width without using variables
  // and turns numberRevs revolutions.
  doInOrder { . . . }
       // Statement taken from program Alice0135a.
  coach .say( ( My width is + ( ( subject = coach .getWidth() ) .toString() ) ) ); duration = 3 seconds
  coach .turn( RIGHT , numberRevs revolutions );
  }
  // Coach reports his current width using variables.
  doInOrder { . . . . . }
       coachesWords .set( value , My width is still );
  coachesWidth .set( value , ( subject = coach .getWidth() ) ); duration = 0 seconds
  widthAsString .set( value , ( coachesWidth .toString() ) ); duration = 0 seconds
  extendedString .set( value , ( coachesWords + widthAsString ) ); duration = 0 seconds
  coach .say( extendedString ); duration = 3 seconds
  }
  // Coach raises both arms and reports new width.
  doInOrder { . . }
       doTogether { . . }
       coach.upperBody.leftArm .roll( RIGHT , 0.25 revolutions );
  coach.upperBody.rightArm .roll( LEFT , 0.25 revolutions );
  }
  doInOrder { . . . . . }
       coachesWords .set( value , Now my new width is );
  coachesWidth .set( value , ( subject = coach .getWidth() ) ); duration = 0 seconds
  widthAsString .set( value , ( coachesWidth .toString() ) ); duration = 0 seconds
  extendedString .set( value , ( coachesWords + widthAsString ) ); duration = 0 seconds
  coach .say( extendedString ); duration = 3 seconds
  }
  }
  }
  }

 


Copyright

Copyright 2007, Richard G. Baldwin.  Faculty and staff of public and private non-profit educational institutions are granted a license to reproduce and to use this material for purposes consistent with the teaching process.  This license does not extend to commercial ventures.  Otherwise, reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP).  His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments.  (TI is still a world leader in DSP.)  In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-