Development environment



Chapter 5: Variables and Objects

This chapter will focus on variables, one of the main concepts of programming languages. After studying this chapter, you will

• understand what is meant by a variable and how variables are used in programs

• understand the idea of datatype

• know what is meant by bit and byte

• learn how bits represent numbers using the binary system and characters using character codes

• start learning about arrays and instances of classes

• gain some understanding of the difference between weakly-typed and strongly –typed languages. JavaScript and ActionScript are both weakly-typed.

• acquire experience using variables and built-in objects in HTML and JavaScript.

Motivating Example

The sample applications for this chapter are all based on simulating the flipping of a coin. The basic game is shown in Figure 1. The player uses the mouse to click on the button labeled TOSS. The program displays a picture of a coin, showing the head or the tail based on an internal calculation simulating random events.

[pic]

Figure 1. Simple coin flip simulation.

NOTE: There is no coin being flipped inside the computer! Instead, the program makes use of a function provided by the developers of JavaScript that produce what appears to be random results.

Building on the basic game, we will show how to keep track of the count of heads and tails. Figure 2 shows the modified game in which an alert box appears with the counts.

[pic]

Figure 2. Coin flip with alert showing the counts.

The next step is to show how the program can be modified to simulate the tossing of a biased coin. This is a coin that has been tampered with to produce heads and tails with different probabilities. Since pseudo-random features are used, this cannot be easily detected since even a fair coin can produce runs of heads or tails. The new program with a way to change the bias and display the results is shown in Figure 3. The alert message has been changed. Note that the bias has not [yet] been changed.

[pic]

Figure 3. Coin toss with new message and bias option.

Figure 4 shows the screen after the bias has been set to .25. This means that heads are likely to occur 75% of the time and tails 25% of the time. See the exercises for suggestions on how to improve this interface. The heads and tails counts are both reset to zero after a change in the bias.

[pic]

Figure 4. Screen shot after many tosses and setting bias on coin.

When a program provides the user/player an opportunity to enter a number, it is good practice to check if what is entered is a number and, furthermore, is a number in the appropriate range. In this case, the conditions of the game require that the number be less than 1 and greater or equal to zero. The next screen shot, Figure 5, shows the result of entering a number greater than 1 or less than zero or text. Notice that the bias has been re-set to 0.5. Responses to errors on the part of a player can be tricky. This will be discussed further in the later sections.

[pic]

Figure 5. Screen shot of error message.

Alert messages require the user/player to click ok in order to continue. If that is not what you want, you can display a message in a text field as shown in Figure 6. This screen shot shows a text field that displays the proportion of expected tails out of total tosses.

[pic]

Figure 6. Results field added to coin toss.

Note the repeating decimal carried out to 16 places. This represents the precision of the float datatype in JavaScript, that is, the significant digits represented by the internal format. This will be explained in more detail later in this chapter. If you did not want the display to show all these numbers, you would use coding similar to the dollars-and-cents formatting in the Coffee Shop example in Chapter 2.

The critical features required by this example include

• simulating the flipping of a coin

• keeping running counts of the heads and tails

• accepting input from the user/player

• dealing with different types of data

Introduction to concepts

The concept of variables in programming can be related to a similar concept in mathematics and science. Think about formulas; for example, the area of a rectangle is the width times the height. When this is written

A = w ( h

where the black circle stands for multiplication, you know that this means that whatever the value of the width is, it will take the place of the w and whatever the value of the height is, it will take the place of the h, and these two numbers are multiplied together to produce the area, represented here by the A. The two symbols, w and h, are variables. Similarly, you have used variables in algebra. In statistics, there is talk of independent variable and dependent variables. The value of dependent variables is derived from, 'dependent on', the independent variables.

A variable is a construct in programming languages that allows you, the programmer, to associate a value with a name. An early definition was to assign a name to a place in the internal memory of the computer. The code would refer to the name, loading and storing whatever value was stored in that position. The newer, more abstract definition, of associating a name with a value better suits the dynamic nature of most programming languages. When discussing applications involving graphical displays, the term internal variable may be used to distinguish between information shown to the users and information accessed and changed by the code.

REAL-LIFE NOTES: The White House is the formal home of the President of the United States. This is true independent of who holds the office. The President has certain responsibilities, independent of the holder of the office. When the Secret Service protects the President, they act (hopefully) independent of whoever the person is that is in office. If you are sick, people suggest that you "See your doctor." This advice assumes that you have a doctor, that is, the phrase 'your doctor' has a current value. When we use phrases such as "the president" or "the doctor" or "my doctor", we are talking about specific people.

The programmer plans and writes code that sets up values for variables and code that makes use of the variables, with the assumption that the values have been set.

The kinds of values that a variable may hold depend on the particular language. This can be said a different way. Values in digital computers are strings of binary digits, called bits. A bit can be a 1 or a zero. The interpretation of a particular string of 1s and 0s varies. The most common ways of interpreting values are as integers (whole numbers), character strings, and true/false values. The term for the different types of values is datatype. Most programming languages support primitive or scalar types and complex types. Primitive types include integer or floating-point number. Complex types involve some kind of aggregation. For example, an array is a set of values, generally an ordered set, in which the individual items are accessed using a special notation with numbers, called indices or index values. A variable can be set to an array. Another complex type is an object, a set of values called attributes or properties and procedures, called methods. We will spend more time on these complex types later in the text.

Going back to our comparisons above, the area formula assumed that the values for width and height were numbers, not necessarily whole numbers. A width could be 12.56. Some may say this is stretching the analogy, but we can say that there is a datatype restriction for the holder of the job of President: this must be a person, at least 35 years old, and a natural-born citizen of the United States. A doctor is a person licensed to practice medicine. Languages that require a variable to be restricted to a datatype are strongly-typed languages. Though the two languages used for the sample applications in this text are not strongly-typed, the sections below will contain samples from strongly-typed languages and explain the benefits to the program of working in a strongly-typed language.

EXAMPLE: The coin flip example will require variables to keep count of the heads, tails and total flips. It also will need a variable to hold the bias value, the value to be compared with the random result.

Description: Variables and datatypes

Variables are ways of associating names with values. The values are held in storage in the memory of the computer while the program is run. The values are strings of bits, that is, 1s and 0s, that are interpreted as different types of data depending on the context and the rules of the language. Three types of values are Booleans, numbers and character strings.

Description: Booleans

A single bit is called a Boolean, especially if it is used to indicate true or false. Some languages support Booleans as a primitive type and use the values TRUE and FALSE (with the capitalization sometimes required and sometimes not) and some do not.

Description: Binary system for whole numbers

A string of 1s and 0s can be interpreted as a binary number, that is, a number using the base two system. Think back to your lessons on place-value for the decimal system,

0 means zero

1 means one

2 means two times one, which is simply two

10 means one times ten plus zero, that is, ten

12 means one times ten plus two, that is, twelve

235 means two times ten squared (ten to the second power) plus three times ten plus five

Why are we writing out the numbers on the right side? To emphasize that the numbers do not change, what will change as the exposition continues is how the numbers are represented.

The binary system uses two in place of ten. Just as decimal representation uses 10 different symbols, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, binary numbers use 2 symbols, 0 and 1. In binary,

0 means zero

1 means one

10 means one times two plus zero, which equals two

11 means one times two plus one times one, which equals three

100 means one times two squared plus zero times two plus zero times one, which equals 4

101 means one times two squared plus zero times two plus one times one, which equals 5

At this point, you may say that binary numbers need to be much longer than decimal numbers, so why do it? The answer is that building circuits in which each position can be in only two states, off or on, 0 or 1, is easier than building circuits in which each position can assume 10 different states. Building more or larger simple circuitry beats building smaller, more complex circuits. Consider the following addition table for binary numbers:

|+ |0 |1 |

|0 |0 |1 |

|1 |1 |0 carry 1 |

This means: 0 +0 is 0, 0+ 1 (either order) is 1, and 1+1 produces a 0 and you carry a 1 to the next column.

The following shows the use of this to add two binary numbers: 101 + 111 (5 + 7 in decimal):

[pic]

Figure 7. Adding in binary

The final answer, 1100, is 1 times two raised to the 3rd power (8) plus 1 times two raised to the 2nd power (4) plus zero plus zero for a total of 12.

Programming languages typically support the whole number datatype using a fixed size of binary field, most typically in units of 8 bits called bytes.

NOTE: the abbreviation is typically B for byte and b for bit. You probably have seen MB for megabyte and KB for kilobyte. These can be ambiguous with M standing either for a million or the power of two nearest to a million, 1048576, and K either 1000 or 1024.

The number of bytes used for whole numbers may be 2 or 4 or 8, with the terms int, short int, or long int, or some equivalent used. For these values to hold positive and negative numbers, one bit must be used to encode the sign, typically 0 for positive numbers and 1 for negative numbers. We can now determine the size of numbers for a given amount of storage. If one byte is allocated as the storage for a number, 7 bits is available for value. This value can go from 0 to 1 less than 2 raised to the 7th power (27 is 128 so 1 less than this is 127). This value is written as all binary 1s. One byte integers, therefore, range from -127 to +127. Doing the same calculation for two-byte numbers

16 bits, 1 for the sign leaves 15 bits

2 raised to the 15th power is 32768

1 less than 32768 is 32767

Two byte integers range from -32768 to +32767

EXAMPLE: The coin flip game will use integer variables to keep track of the counts.

Description: Floating-point numbers

Moving on, not all numbers are whole numbers! It can be necessary to express fractions or what probably was called mixed or decimal numbers in your grade school: numbers with a whole and a fraction part. The common approach in computing is to use floating-point numbers. The bits reserved for floating point number are divided into a bit for the sign, space for the significant digits, and space for the power, including its sign. A floating point number (using decimal values for this description) has more than one representation. For example, the number 2.75 is

2.75 times 10 raised to the 0th power

27.5 times 10 raised to the -1st power

.275 times 10 raised to the 1st power

A language establishes a convention for the handling for floating point numbers. Generally, you, the programmer, do not need to be aware of this convention.

EXAMPLE: The coin flip game will use a floating-point variable to hold the fraction used when testing if a head or tail is to appear.

TECHNICAL NOTE: One implication of this form of representation is that there is a limit on the precision, the number of significant digits, for any number. This is significant for repeating decimals such as one third and numbers such as pi that are non-repeating decimals. An alternative approach could be to represent fractions as two integers with the number value being the result of dividing one by another. The value a third would be represented by the pair (1,3), this approach has merit because the precision is not limited. This approach is used in specialized systems. The floating point format is the standard.

To summarize the issue of representation for numbers: the size limits the absolute value in the case of whole numbers and limits the precision with the mixed numbers.

Description: Character data

The last category of values for discussion here are character strings, often shortened to just string. Programming languages have facilities for representing values such as

"Logic", "My logic" and "1024".

The first example is straight-forward: it is the 5 characters L, o, g, i and c. The second example has one subtlety: it is 8 characters, with the third one needing to be a representation of a blank. The third example is the 4 character string, the character for 1, the character for 0, the character for 2 and the character for 4. This is not the same as the number 1024!

Pairs of single or double quotation marks can be used, but you cannot write

"Logic'

You can write

"She said, 'Hello'"

As is the case with all data, programming languages use bit strings to represent individual characters. This was once straight-forward: a byte (8 bits) represented a character. Typically, the coding was something called ASCII code or Extended ASCII. In this code, the binary string for a few sample values are

A 01000001

B 01000010

C 01000011

(blank) 00100000

. 00101110

? 00111111

NOTES: Now there is an attempt to represent a much, much more ambitious set of characters, namely the characters for all the world's languages! The effort is called UNICODE. There are versions of UNICODE that use 8 bits and some that use 16 bits. UNICODE is considered a superset of ASCII; that is, the 1st through 127th code points of UNICODE represent the same characters as the 1st through 127th code points in ASCII.

Programming languages differ in their treatment of strings of characters. In some, there is native support: strings are considered a primitive type. In others, characters are the primitive type

'a', 'A', 'b', '/', etc.

and strings of characters such as

"Programming"

are implemented as arrays, that is, sequenced sets of characters.

Yet another approach to implement strings as instances of a special datatype called a String class. In some languages, a variable is set (declared) to be a string of a fixed size. In others, a variable is set to be a string and can hold different size strings during the program. Some languages make use of a special end-of-string character and others store a pointer to the string and the current string length. You do not have to know all the specifics of how strings, or numbers, or Booleans, for that matter, are implemented, but you will need to find out if you can assign a new string of a different size to a string variable, how to access the length, how to check if two strings are equal, and other operations.

In JavaScript, and many other languages, the individual characters making up a string are numbered starting from zero. You can get the length of a string using the length property. If

var title = "Programming Logic";

then

title.length produces the value 17

The characters within the string are referenced using what are termed index values. In this situation, valid index values include zero through 16. You can extract a piece of a string using the method substring.

title.substring(3,6) produces the string "gra"

that is the 3rd character up to but NOT including the 6th character.

An alternative way to establish a variable that will hold a string value is

var title = new String();

similar to the way Date objects were defined. However, the approach of immediately assigning an actual string constant, a literal string, is more common.

Description: Variable declarations, including arrays and strings

Now that you have an introduction to datatypes, here are some ways that different languages require you to set up a variable. One big difference between languages is that some require a variable declaration and some do not. JavaScript in HTML documents and ActionScript in Flash projects do not require a declaration of datatype at all and do not require any declaration in some situations. If and when you use a variable, the language processor will set it up. However, certain situations require you to use a declaration to ensure that the variable is accessible and maintains its value inside and outside of functions. This will be demonstrated in the sample applications.

Languages that require declarations with datatypes generally allocate the space required for the variable at the time of the declaration. In Java, a strongly-typed language, the following are examples of declarations of variables:

boolean ready; // a single bit

char symbol; // Unicode character

byte littlenum; // 8 bits number from -128 to 127

short counter; // 16 bits number from -32768 to 32767

int counter2; // 32 bits number from -2147483648 to 2147483647

float cost; // 32 bits, exponent -45 to +38,

// roughly 9 (decimal) significant digits

Java has so-called modifiers that can be placed in front of the type indicator. One modifier is final. This specifies that the variable will not be changed; it is a constant. Other modifiers control access to the variables. The definition of methods, that is, procedures defined in classes, also can have modifiers controlling their access.

You can set the initial value of the variable in the same statement.

boolean ready = true;

char symbol = 'a';

float cost = 10.25;

Arrays in Java and other languages are sets of values in which an individual value is accessed using an index. A variable holding the population of each of the fifty states, with the numbering determined elsewhere would be declared

int state_populations[] = new int[50];

This statement sets up state_populations to be an array. The left side sets up the variable as an array in which the individual elements are of type int. The right side does the actual generation of the array: space is allocated for 50 elements of datatype int. It does not put in any values; that is, it does not initialize the variable, but makes room for it. Code later on can include individual assignments. The following statement

state_populations[5] = 1000000;

assigns the value 1000000 to the item in the array corresponding to the index value 5. Generally, this would be the 6th value, since index values start at zero. Actually, a statement such as this one with constant values would be atypical. More common would be

state_populations[co] = population;

where co is a variable with an integer value between 0 and 49 and population holds an integer value as well.

An alternative way to declare an array and do the initialization is:

float costs[] = {10.50, 8.25; 7.00};

Declaring a variable to be a string is similar:

String first_name ="Joseph";

This interlude of Java examples is to show you an example of a strongly-typed language. You may see the requirement to declare variables in this detail as a burden. However, what happens in languages such as Java is the following: programs go through a compilation step. That step does two things: it performs checks on the program and, if the program is okay, translates the code into a format in which it can be executed. The checking includes making sure that variables are used in the way in which they are declared. This means that if you made the mistake of using a variable that is to hold the name of product, a string, as opposed to the cost of the product, a number, the compiler will flag that statement. Strong-typing turns many logical errors into syntactic errors that are easily identified. Compilation usually goes along with strong-typing and interpretation goes along with weak-typing, also called dynamic typing. The compilation process produces code that is more efficient and, therefore, faster than what occurs in the case of the weakly-typed, also called dynamically typed languages, such as JavaScript or Python.

JavaScript and ActionScript also have statements for declaring variables. The reserved keyword var is used and the statement may or may not include initialization.

var cost;

var cost = "1.50";

var first_name;

var first_name="Joseph";

The location of the declaration statement, the var statement, can be outside of any function definition, making this a global variable that can be accessed by any code, both inside and outside of functions. The variable persists independent of function calls. If the declaration is inside a function, then the variable is local to that function and goes away when the function stops. Java does not have global variables: everything is within functions or within class definitions[1]. Variables also could be defined within what is named the main method, but the practice in languages such as Java is to discourage the use of such variables.

The differences can be summarized in the following table:

|Language |Classification |Declarations |Checking |

|Java |Strongly-typed |Always required |Compile time & run time |

|JavaScript |Weakly-typed |May be necessary to |Some differences with |

| | |distinguish global from |browsers. Errors caught are |

| | |local, do initialization |not automatically displayed.|

|ActionScript |Weakly-typed |May be necessary to |Flash will display syntactic|

| | |distinguish global from |errors such as mis-matched |

| | |local, do initialization |brackets. Does not check on |

| | | |datatypes. |

Reading Checks

1. Define variable.

2. Describe what is meant by a variable declaration.

3. Describe what is meant by datatype.

4. What is an example of an integer value, a floating-point value, a Boolean, a character string?

5. Describe what is meant by an array?

Now on to the working examples.

Application

This section reviews uses of variables in previous chapters and then goes on to describe construction of coin toss games using HTML and JavaScript.

Review of previous examples

In the Flash/ActionScript Directions example in Chapter 1, a variable named nextstep was changed so that it always held the frame number of the next step. This variable was a global variable, declared with a var statement in frame code outside of any function, though to be absolutely accurate, the var statement was not necessary since the next line in the very first frame assigned a value to nextstep and would have caused the language processor to set up the variable for global use. The variable was used in the statement

goToAndPlay(nextstep)

appearing in the on (release) code, the event handler for clicking the button.

The Calculation example in Chapter 2 made use of properties of built-in objects, for example, in the statement (that was later changed):

f.sum.value = f.one.value + f.two.value+f.three.value;

The datatype of value attributes of tags is string. The chapter showed that the expression on the right-hand side of this statement would perform string concatenation and not addition of numbers, demonstrating that you do need to think about datatypes even in weakly-typed languages. The Coffee shop example made use of variables in the calculation for formatting a string to represent dollars and cents. The use of HTML attributes brings out the issue that some data is visible to the user (also known as customer or player) and some is maintained in the form of internal variables.

Chapter 3 made use of another built-in construct of HTML and JavaScript, namely the Date object. The code

var d = new Date();

sets up a variable named d with value of datatype Date. Just as there are values of type integer, bit, character, and so on, there are values of type Date. Recall that this Date class produces an object that holds date, day, and time information. The absence of anything between the parentheses following Date signals the language processor to create a Date based on the current time. Formally, this is an object of the Date class. The value of d is an object holding the current value. In Chapter 3, methods of the Date class were used to extract a number that the program used to choose between two backgrounds for the web page.

EXAMPLE: The Find Daniel application of Chapter 4 made use of built-in constructs of HTML without requiring much JavaScript coding. Adding the refinement to stop the timing event required the use of the variable tid. This variable was declared outside of any function, making it a global variable. As a result, it could be set in the starttiming function but persist after that function had finished. It was used in

onClick="clearTimeout(tid); window.open('daniel.html');"

to stop the timing event from being monitored and handled after the clicking on the correct area had been detected.

Plan of attack for coin toss games

The organization of each of the applications is

html

head element

title

script element containing variables and function definitions

body element

img tag to hold pictures of head or tail

one of more form elements

input elements for text input or output

input element for submit button

Development starts with the basic coin flip simulation for a 'fair', unbiased coin. This does not make use of any variables and has no text input or output. One reason for this is that the value .5 appears as a constant in the code. The next stage is to add the feature to display the running counts. The design for this makes use of internal variables with the results displayed using an alert message. The third stage adds the capability to simulate a weighted coin with a specific weighting. This is done by adding an element in a new form element to allow the player to enter a value. The value is to be a fraction, a floating point number and the function that handles the onSubmit for the new form must perform a check on the input. The results are displayed using an alert message. The final stage changes the reporting to be done using an field (now used for output) in a third form element.

Use of concepts in implementation

The base application makes use of one function, toss, containing an if statement. The function ends with the code:

return false;

This ensures that the HTML page is not refreshed to show the initial image.

NOTE: The requirement to have the function return a special value so that the screen does not change back to the original is part of the workings of HTML and browsers and would not apply to other programming languages. However, it is necessary to pay attention to the timing of the display and other events.

The code for this application starts with an image file for a blank image. One could certainly argue that either the head image or the tail image would be appropriate. The onSubmit event for the form is to call the toss function. Note that the form only contains the element producing the button for submission.

coin toss

function toss() {

if (Math.random()>=.5) {

window.document.coin.src="head.gif";}

else {

window.document.coin.src="tail.gif";};

return false;

}

The next step is to keep track of the counts of heads and tails and to display these counts. The decision was made to use internal, global variables for this purpose. The variables are declared and initialized, each to zero. Within the appropriate clauses of the if statement, the right variable is incremented using the shorthand operator ++. The results are displayed each time using the alert function. Notice that the parameter for this function consists of a string constructed by concatenation of constants and variables. The JavaScript process knows to turn the numbers into strings based on the context. In some strongly-typed languages, you would need to use a function to produce the string form of a number.

coin toss

var heads = 0;

var tails = 0;

function toss() {

if (Math.random()>=.5) {

window.document.coin.src="head.gif";

heads++;

}

else {

window.document.coin.src="tail.gif";

tails++;

};

alert("Count: "+heads+" heads and "+tails+" tails.");

return false;

}

The next application allows the player to produce a biased or weighted coin. This is done using a new function, called setbias, invoked upon submission of input from a new form. The form has the name "b" and an element with the name "sbias". This function resets the heads and tails variables back to zero. This is done using the statement

heads = tails = 0;

This compressed for works because an assignment statement is actually an expression with the value whatever was assigned. So the variable heads also is assigned 0.

NOTE: You do not need to strive for brevity by using tricks such as combining assignment statements or using the shorthand operators such as ++. It is generally the case that programmers spend more time looking at their code than writing it, so use what is meaningful to you.

The code begins

coin toss

var heads = 0;

var tails = 0;

var bias = .5;

function setbias() {

heads = tails = 0;

The next task is to take the value that the player entered and assign it to the variable. However, it is necessary to convert the text entered by the player into a number, specifically a floating point number. This is done using the function parseFloat.

bias = parseFloat(document.b.sbias.value);

This value is assigned back to the visible element, turning back into a string. Notice that this will mean that if the player enters .25, it will be displayed as 0.25.

document.b.sbias.value = bias;

The player may have entered a number that was out of the acceptable range. The following if statement checks this and also checks if the original input was something other than a number by using a built-in function isNaN (standing for "is not a number"). In the case of any bad input, the bias is reset to .5 and an alert message issued.

if (bias>=1 || bias =bias) {

window.document.coin.src="head.gif";

heads++;

}

else {

window.document.coin.src="tail.gif";

tails++;

};

alert(heads+" heads out of "+(heads+tails)+" tosses." );

return false;

}

The body element has a second form element, with an element for the player to enter data and an element for the submit button.

| |opening body tag |

| |img tag named coin |

| |opening form tag for the TOSS button. When it is |

| |clicked, the toss function will be called. |

| |button with label TOSS |

| |close form |

| |opening form for second form. When its submit button is|

| |clicked, the setbias function will be called. |

| |field for the player to enter a value. The initial |

| |value is .5. |

| |button with label Set bias |

| |close form |

| |close body |

The final example outputs the results a different way, using yet another form element, which has an input element named results. The setbias function erases any previous contents in the element named results by assigning the empty string, "", to document.r.results.value.

| |opening tags |

|coin toss |title |

| |opening script element |

|var heads = 0; |initialize count of heads |

|var tails = 0; |initialize count of tails |

|var bias = .5; |initialize bias |

|function setbias() { |header for function |

| heads = tails = 0; |re-initializes the counts |

| bias = parseFloat(document.b.sbias.value); |sets the bias to the value entered by |

| |player, forcing it to be a floating |

| |point number. If it was not a number,|

| |it would be set to zero. |

| document.b.sbias.value = bias; |re-display value so player notices if |

| |the entered value was incorrect |

| document.r.results.value = ""; |re-set results to empty string |

| if (bias>=1 || bias =bias) { |Compare random result to bias |

| window.document.coin.src="head.gif"; |... display head |

| heads++; |increment head count |

| } |close clause |

|else { |else |

| window.document.coin.src="tail.gif"; | … display tail |

| tails++; |increment tail count |

| }; |close clause |

|document.r.results.value = tails/(heads+tails)+" ratio of tails out of "+(heads+tails)+" |compute and display the tails ratio |

|tosses."; | |

|return false; |return false to prevent reload of |

| |page |

|} |close function |

| |closing script tag |

| |closing head tag |

The body now has three form elements. It would be possible to combine the form named "r" with one of the previous forms since it does not require its own submit button.

Reading Checks

1. How do you set up a button using an HTML form?

2. How do you set up a field for a user to enter data for an application?

3. What does onSubmit do in the tag?

4. What does parseFloat achieve?

5. What would be the value of isNaN(X) if X was "20" ? If X was "ABC"?

6. If the variable X held the value 5, what would be its value after the statement X++ was executed?

What can go wrong

One thing that easily could go wrong in these types of applications is neglecting to do the conversions from strings to numbers. The weakly-typed languages have advantages in ease-of-use in not requiring typing and making many conversions automatically. However, sometimes the runtime system cannot figure out that the programmer wants a conversion (also called a cast) and then it needs to be programmed explicitly. This was done by the parseFloat command in the application.

The browser can cause another type of problem. When you use the Web, you can click the re-load button. This causes the browser to open up and interpret the HTML document just as it did when you typed in the address or use a window to find and open the file. The problem is that the form data may not be changed. This can cause the anomaly in this example that the internal variable named bias is reset to .5 but another value appears on display. To fix this, the code could include

document.b.sbias.value = bias;

right under the statement

var bias = .5;

Chapter Summary and Reflection

This chapter focused on the critical programming concept of variables and how data is represented in computers. This included nitty-gritty discussion of bits and bytes, different types of numbers such as integer versus floating-point, the binary system, Booleans and character strings. Arrays, which are sets of values, were introduced. Comparisons were made between strongly-typed and weakly-typed languages.

You may ask why the counts of heads and tails could not be displayed directly on the Web page and updated in place, so to speak, instead of using internal variables. To perform this addition, it would be necessary to use code such as

document.c.headscount.value = 1+parseInt(document.c.headscount.value);

assuming that c was the name of the form and headscount the name of the element within the form. This certainly could be done. However, the approach shown here allowed us to compose the display in another way. In any case, many applications are best done with internal variables not on view by the user.

An important lesson from the sample applications in this chapter is the progression from the simplest case to more elaborate cases. Most programming is done in an iterative fashion.

If you were a programmer

Simulations of events involving pseudo-random, also called stochastic, calculations are common in industry and in research. There are even actions corresponding to changing weightings. For example, banks need to test if their networks can handle variable traffic at ATMs located throughout the city. Simulations are used to determine optimum places to locate stations such as ATMs. Market research firms use simulations to gather data on products, ads and promotions.

Some industrial applications make use of the equivalent of alert windows, that is, messages that need to be closed; others make use of messages on the screen that do not require explicit attention. You need to consider each case and decide what is required. Alert windows, or the equivalent in other languages (trace is the function for Flash) are very useful during debugging.

The complicated rules governing access and persistence of variables may strike you as misguided. You may say, "If my code makes use of the variable tid both inside a function and inside the body as part of event handling, I intended this to be the same variable." The problem is that you and your colleague down the hall or around the world may both be working on parts of the same application. If you use the same variable name for different values, your program will not work correctly. It is best if variables and other entities are assumed local and, therefore, distinct unless explicitly set up to be shared.

What's next

All the rest of the examples will include use of variables. The next chapter expands on the use of programmer-defined functions, this time with a Flash example. The following chapter demonstrates the use of variables to hold data that defines the state of the game. The next chapter demonstrates the use of arrays.

Exercises

1. Calculate the binary equivalents of 13, 25, 133, 678, 3000, 4096

2. Calculate the decimal equivalent of the binary numbers: 100001, 101010101,

1111110000000

3. Calculate the binary equivalent form, perform binary addition, and then convert the answers back to check:

a. 2+2

b. 135 + 402

c. 1028 + 5111

4. Using what you already know about decimal arithmetic, calculate the binary equivalents, perform binary subtraction, and then convert the answers back to check:

a. 13 – 4

b. 156 – 111

c. 2678 – 1115

5. What are variables used for in programming languages? Give examples from the sample applications in this chapter.

6. Name and describe different datatypes.

7. True or False: Strongly-typed languages require the declaration of variables, including specifying the datatype.

8. True or False: JavaScript is a strongly-typed language.

9. Define bit. Define byte. What is the difference?

10. What is the difference between 12 and "12"?

11. If the variable a holds the value "24" and the variable b holds the value "45", what is a+b?

12. What is the difference between the values true and "true"?

13. How is the character 'A' represented using the ASCII code? How is the character 'a' represented using the ASCII code? How is the character of a blank space ' ' represented using the ASCII code?

Projects

14. Do research on-line to find out how UNICODE represents the Latin alphabet. (Hint: there is a UTF-8 and a UTF-16 coding.)

15. Do research on-line to find out how UNICODE represents a kanji character.

16. The text gave some examples of Java declarations. Do research to find the format for declarations in other languages (c, c++, Pascal, or are possibilities).

17. Take the coin flip game and using internal variables, keep track of the longest runs of heads or tails.

18. Change the form of input from the player for setting the weighting of the coin to be two integers, representing the relative amounts: the player/fixer would enter a tail number (say 3) and a head number (say 2) to indicate 3 tails to 2 heads. After checking that the entries were both positive numbers, your code would calculate that the bias number would be 3/(3+2).

19. Do informal research among friends and colleagues to determine what would be the best way to communicate the mechanics of the weighting/bias of the coin.

20. Design and build an application that simulates the throwing of two coins for a game in which the results are with "match" or "not match". Use images to illustrate the game.

21. Building on the last project, allow input for the player to 'call', match or not match. A displayed text result would be "win" or "lose". Coin images would be displayed, also.

For teachers only: Tips for Teachers

I often do the base coin flip application as a whole-class follow-along exercise. I also do a Flash version. I then ask the students a series of questions on how to weight the coin to have twice as many heads as tails, three times as many, etc. Many students find it difficult to calculate the decimal numbers that would satisfy these conditions.

The best way to demonstrate the string versus number datatype issue is to not do the conversion and see the heads variable take on values like: "0111111" and so on.

The iterative method of developing programs is difficult to get across by lecturing. Modeling the process through a progression of examples such as this is the best way.

-----------------------

[1] A complete example of Java with instance variables defined in a class definition is in Chapter 7.

-----------------------

1 0 1

1 1 1

1 1 0 0

1 1

1 + 1 produces 0 carry 1

1 + 0 produces 1 adding in 1 (the carry) produces 0 carry 1

1 + 1 produces 0 with carry 1 to the next column,

the 0 + the carry in the 3rd column yields a 1

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download