Basic Smalltalk terminology. Simple message expression. Using LearningWorks. Programming Tutorial.



More Tutorials
C Programming Tutorial
T223

HTML Tutorial & Web Design
T170,T171 and TT180

Search this site

Home

 

Tutorials
| 1. Starting Smalltalk, and Terminology | 2. Precedence Rules | 3. Classes - Strings | 4. Class Browser | 5. Variables | 6. Error Messages | 12. Control Structures | 16. Dialogs | 23. Collection class | 39. OpenGUI |

 

Information
| Smalltalk Books | Student Software & Books | Hints & Tips | Sites | Download Smalltalk | Coloured code | Download Documents | ASCII Codes |

 

Smalltalk Index

 

 

 

Student
Licence Software
at special prices

 

Updated 10 June01

Contents


Introduction

Conditional Expressions
Comparison Operators=~===< <=> >=

Blocks
Use of Periods



Decision making methods ifTrue: ifFalse:
  ifTrue:ifFalse: ifFalse:ifTrue:



methods timesRepeat  
whileTrue: whileFalse:



Other methods & (logical and) | (logical or)
  between:and: exists isEmpty isInteger isNil isNumber isReal isVowel
  not Dialog confirm: value



  Answer to questions Exercise Solutions

Introduction

Students who have programmed in other languages will find this tutorial fairly easy.

 

Students new to programming MUST ensure that they understand how the control structures of iteration (loops) and decision making (branching) work.

 

In order to help new students, I have written a lesson showing how these structures work in English, with an example of making a cup of coffee. New students should click on this link, Loop and Decision Structures, read this extra lesson then click your browsers back button to return to this tutorial number 12.

For the exercises in this lesson. Start the LearningWorks program provided by the OU (Open University) M206 course. Use either LearningBooks LB 12, 13 or 14.
Or use an alternative Smalltalk program to LearnWorks.

 

Up to now all the expressions that have been used have been executed one after the other, in the order that they were written, top to bottom.
They have consisted of:

  • Simple expression(s).
  • Cascading expression.
  • Expression series.

Question 1. What punctuation is used to separate the expressions in an expression series?
Go to Answer 1.

 

Question 2. What punctuation is used to separate the messages in a cascading expression?
Go to Answer 2.

 

Question 3. What is the difference between an expression series, and cascading messages?
Go to Answer 3.

 

In order to make computers do more than execute such very simple programs you require methods that will allow you to:

  1. Repeat sections of code, a number of times. Such code is often referred to as a loop.
  2. Branch. Branching refers to code where some decision making takes place. This is done by coding a Boolean Conditional Expression. This results in only certain sections (branches), of code being executed depending on the result of the Boolean condition, i.e. a condition that evaluates to true or false
  3. Or a decision making loop.. I.e. Methods that provide a combination of Repeating and branching, they repeat sections of code depending on the result of a conditional block.
This is where coding becomes exciting, as you learn to look at extremely complex situations, which you break down, into very simple steps. These simple steps can then be coded using the control structures that you will learn about in this lesson.

Top of Page

Conditional Expressions

Conditional Expressions sometimes called Boolean Conditional Expressions return a boolean answer of either true or false.
You can think of conditional expression as asking a question. examples of these expressions could be:-

Smalltalk conditional expression Meaning
(object1 = object2)
Is object 1 equal to object 2
(object3 < object4)
Is object 3 smaller than object 4

Note that the parenthesis surrounding a conditional expression is optional. The course convention is to use parenthesis.The use of parenthesis along with indentation makes code easier to read. This in turn means that it is easier to debug if it is not working.

Top of Page

Comparison Operators

Comparison Operators Meaning 2 Examples of each Comparison Operators Example answer
== Same object as
'a' == 'a'
2 = 2
false

 

true
= Equal. In smalltalk = is a comparison operator, do not confuse it with the assignment operator :=
'a' = 'a'
 
2 = 2
true

 

true
~= Not equal
'a'  ~= 'a'
2 ~= 2
false

 

false
< Less than
'z' < 'Z'
3 < 4
false
true
> Greater than
'z' > 'Z'
3 > 4
true

 

false
<= Less than or equal to
'a' <= 'z'
2 <= 2
true

 

true
>= Greater than or equal to
'a' >= 'z'
2 >= 2
false

 

true
not not is a boolean, rather than a comparison operator. changes true to false, or false to true. It is easier and clearer to use ~=
('a' >= 'z') not
 
(2 >= 2) not
true

 

false

Messages that answer true or false

The following message selectors are in a way comparing. They answer with either true or false, and therefore can be used as a boolean conditional expression, with our control messages that follow in this tutorial.
Selector What it does Example Example answer
between:and: Check if an object is in an inclusive range. Can be a neat alternative to using (4 >=2) & (4 <=4) 4 between: 2 and: 4 true
exists true if named file exist    
isEmpty true if the object is empty    
isInteger true if the object is an integer    
isNil true if the object is equal to nil, e.g. not initialized    
isNumber There is No isNumber method, check out isReal    
isReal isReal answers with true if the object is a Real number. This means essentially that it's an instance of a subclass of Number.    
isVowel true if the object is a vowel    
Dialog confirm: see Tutorial 16. Dialog confirm:    

Top of Page

Blocks

Most of the messages that you are going to look at in this lesson use blocks. A block of code is enclosed in square brackets [ ] . The brackets are required, they mark the start and end of the block.
  • The start of a block is denoted by the opening bracket [
  • The end of a block is denoted by the closing bracket ]
  • A block can contain any number of valid executable expressions or any number of comments.
  • Each expression must end with a period except for the last expression in the block, when the period is optional.
  • The whileTrue: or whileFalse: messages require the use of a block both in front of, and after the message selector.
  • A block could be reguarded as a method without a name.
  • Blocks belong to the class BlockClosure.
  • One or more of the expressions may be a further construct that includes [aBlock] that is nested within the block.
  • There are many other methods, besides those discussed in this lesson that require blocks.
  • The blocks used in this lesson are required, but any expression, or expression series, can be turned into a block by enclosing it in square brackets. The message value is often used with this type of block. e.g.
    ['abcd' asUppercase] value

Tips when using blocks, especially if you have nested blocks.
  • When typing in the start [bracket, type 3 spaces then the end ]bracket. This ensures that you do not forget it.
  • It may help if you also insert any required periods at this stage. Or at least think about where they will go.
  • Then insert your code between the 2 square brackets. This makes the insertion of nested blocks much easier.
  • Use indentation if your block contains an expression series.
  • Use further indentation for any nested blocks.

Top of Page

Use of Periods


In the following methods, pay special attention to periods, especially where they are NOT needed. As the code starts to get more complicated, students appear to forget the basics.
  • Periods are used to separate expressions, in a series of expressions.
  • Expressions examples
    • Receiver message.
    • Receiver keywordMessage: argument.
    • Receiver keywordMessage: argument keywordMessage: argument.
  • Blocks can often contain expression series.
  • A period is not used between a receiver and the message sent to that receiver. Note:- Boolean conditions or Boolean condition blocks are receivers.
  • ifTrue:ifFalse is an example of a keyword message selector with more than one argument. A period is not used to separate keywords with more than one argument, although a period may be used within either, or both of the 2 blocks, if more than 1 expression is required.
  • The wrong positioning of periods will lead to an error message. You may like to experiment with wrong positions to build up your error message list.

 

Top of Page

Decision making

Sometimes called Conditional Logic.
  • Conditional logic allows a selected portion of code to be executed, depending on the value of a boolean condition. This control structure is known as branching.
  • A Boolean condition can be any expression that results in a value of true or false
  • The keyword message selectors that can be used are:-
        ifTrue:    ifFalse:   ifTrue:ifFalse:   ifFalse:ifTrue:   whileTrue:   whileFalse:

 

ifTrue: and ifFalse:


The general format for ifTrue: and ifFalse: are Examples Example Answers
(aBooleanCondition)
    ifTrue: [ Execute this block of code only if the condition is true ] .

Although not required, by convention the conditions are enclosed in parenthesis ( ).
( 4 = 4 ) 
    ifTrue: [ ^true ] .
true
( aBooleanCondition ) 
ifFalse: [ Execute this block of code only if the condition is false ] .
( 4 < 4 ) 
    ifFalse: [ ^false ] .
false
  • a Boolean condition can be any expression that results in a value of true or false.
  • aBlock of code may be a
    • A single simple message expression
    • A cascading message expression
    • A message expression series.
    • A another nested control type structure such as ifTrue:, timesRepeat: whileFalse: etc.
    • A combination of the above

Top of Page

ifTrue:ifFalse: and ifFalse:ifTrue:

  • These 2 methods do exactly the same thing.
  • The only difference is the order of the blocks.
  • If one block has much more code in it, possibly with additional nested blocks, I would personally use the expression that would allow the complicated code to be in the second block. An example of this is the solution to Exercise 1d.
The general formats for an ifTrue: ifFalse: expression is Examples Example Answers
( aBooleanCondition )
    ifTrue: [ Execute this block of code only if the condition is true ]
    ifFalse: [Execute this block of code only if the condition is false] .

Note:-
  • No periods at the end of the first 2 lines.
  • In the ifFalse:ifTrue: structure.
    the ifFalse:is placed in front of ifTrue: as in the example on the right.

 


( 'a' = 'a' ) 
    ifFalse: [ ^false ] 
    ifTrue: [ ^true ].

 

 

true

Top of Page

Question 4. In the example
( 4 = 4 ) 
    ifTrue: [ ^true ] .
What does the caret do?
Go to Answer 4.

 


Question 5. In the example
( 'a' = 'a' )
      ifTrue: [ ^true ]
      ifFalse: [ ^false ] .
^'Another answer'

State why the 3rd answer 'Another answer' could never be returned.
Go to Answer 5.

 

How to obtain a 3rd answer is discused later in this tutorial.

 

You will be coding how to return 1 of 3 different answers later in this tutorial.

Top of Page

& (Logical AND)


More complicated conditions can be created by combining more that 1 condition using the boolean operators AND or OR.

 

In smalltalk & is used for AND.
The general formats for using & is
( (condition 1) & (condition 2) ) 
      ifTrue: [ "Code here is evaluated only if both conditions are true" ]
      ifFalse: [ "Code here is evaluated only if  either one or both conditions are false" ] .

| (Logical OR)


In smalltalk | is used for OR.
On UK keyboards the | key is usually the key to the left of the Z key, it is used in conjunction with the shift key. The symbol marked on the key usually has a small gap in the middle of the vertical line. The general format for using | is
( (condition 1) | (condition 2) ) 
ifTrue: [ "Code here is evaluated only if either one or both conditions are true" ] ifFalse: [ "Code here is evaluated only if both conditions are false" ] .

 

Summarised Rules


When using & (logical AND) both must be true to produce a true answer.
When using | (logical OR) either or both must be true to produce a true answer.
In both the above anything else is false.

 

Question 6. In the following table, look at the boolean conditions . Work out whether condition 1 and 2, are true or false and enter your answer into their respective columns.. Looking at these 2 results you have entered, and noting whether the expression is an AND or an OR structure. Use the Summarised Rules to work out the answer that will be returned in the last column
Qu.
No.
boolean conditions
(condition1) (condition1)
condition1 condition2 answer
e.g.
 ( (4 < 6) & ('a' > 'c') )
true false false
a
 ( (4 < 6) & (21 > 19) )
     
b
( (4 < 6) | (21  > 19) )
     
c
 ( (4 < 6) & (21 < 19) ) 
     
d
( (4 < 6) | (21  < 19) )
     
e
( (4 > 6) & (21 < 19) )
     
f
( (4 > 6) | (21 < 19) )
     
g
( ('c' > 'a') | (21 < 19) )
     
h
( ('c' > 'a') & (21 < 19) )
     
i
( ('c' = 'c') | (21 < 19) )
     
j
( ('c' == 'c') | (21 < 19) ) 
     
k
( (4 < 6) & (21 ~= 19) )
     
l
 ( (4 < 6) & (21 < 19) not ) 
     

Go to Answers 6.

 

The comparisons above have all been very simple. Normally conditional expressions use either 1 or 2 variables or objects.

 

Examples
( numer1 < number2 ) 
( number3 >= 5 )
( frog1 = frog2 ) 
( aLetter < 'm' )

This makes it harder to see whether the expression will answers with true or false. The value of the variable must be worked out.

Top of Page


Exercise 1a. Using &, ifTrue:ifFalse. Testing Code.

 

The following code using the logical AND and the variable age. The code checks if the the age is within the teenager age group 13-19, and 1 of 2 answers is returned.
Question 7a. Work out what answer will be returned?
"T12. Exercise 1 (a)  Using &, ifTrue:ifFalse"
|age|
age := 24.
( (age >= 13) & (age < 19) ) 
    ifTrue: [ ^'You are a teenager' ]
    ifFalse: [ ^'You are NOT a teenager' ] . 
		  
Go to Answer 7a.

 

Copy the above code and its "T12. Exercise 1a. Using &, ifTrue:ifFalse" comment, and paste it into the workspace.
Evaluate it, check that the correct answer is returned, then

Test the Code.


Question 7b. List the ages that you would use to test this code is working correctly.
Go to Answer 7b.

 

Check that the code is working correctly by changing the age of 24 and evaluating with the different ages given in the Answer 7.

 

Go to Ex.1a. test results.

 

correct the following section of code
 (age < 19)
		  
to
 (age <= 19)
		  
Well done if you had already spotted this error.

 

Question 7c.
Will (age <=19) produce the same results as (age < 20)
Go to Answer 7c.

 


Test your code with 19.25.
We are only dealing with integers at the moment, therefore we will leave the the expression at (age <=19).
Later in this tutorial is a message that will check if an object is an interger.
Later in the course you will learn how to program input checks into your code that will prevent an entry such as 19.25, '18', or 'twelve' etc.

 

Top of Page


Exercise 1b. Using &, ifTrue
  1. In the Workspace Click at the end of code you have just evaluated, to ensure that it is not highlighted.
  2. Press the enter key a couple of times to insert 2 blank lines in the Workspace.
  3. Copy the corrected code and comment you use in Exercise 1 (a).
  4. Paste into the Workspace after the 2 blank lines.
  5. Alter the comment of this pasted copy to "T12. Exercise 1 (b). Using &, ifTrue only"
  6. Delete only the message selector, ifFalse: not the rest of the code on that line
  7. Your code should now look like:
    "T12. Exercise 1b.  Using &, ifTrue"
    |age|
    age := 14.
    ( (age >= 13) & (age <= 19) ) 
        ifTrue: [ ^'You are a teenager' ]
        [ ^'You are NOT a teenager' ] . 
    		  
  8. Evaluate and note that deleting ifFalse: has introduced an error.
    • This error is already listed in the list of error message.
    • This error is NOT in the line [ ^'You are NOT a teenager' ]. Remember the message selector has been changed from ifTrue:ifFalse: to ifTrue:
  9. Correct this very simple, and very common error.
  10. Go to solution for this error
  11. Ensure the age is 14, then check that the code is working.
  12. At this stage you may be happy with the code, but it is NOT fully tested.
  13. Change the age back to 24 and evaluate.
  14. The answer BlockClosure [] in Text Editor Evaluation is in the answer pane, this is NOT the answer required
  15. Slightly alter the remaining code in the last line so that the correct answer is returned.

Go to final solution Exercise 1b.

 



Exercise 1c. Obtaining 3 different answers.

 

You are now required to write some code that will return 1 of 3 possible answers, using code from the previous solution as a start.
  • 'You are a teenager'
  • 'You are too young to be a teenager'
  • 'You are too old to be a teenager'
  1. Copy and paste the previous solution code again after a couple of blank lines.
  2. Delete the last line.
  3. There are many different ways of coding this.
  4. The code for the 'You are a teenager' result is already coded
  5. As a guide on how to complete this exercise you should use the following in the code you must:
    • Amend the Exercise comment, to something suitable
    • Add 2 additional condition expressions. One for each of the other possible answers.
    • each condition expressions requires an ifTrue structure.
  6. Now attempt your solution in the Workspace.
  7. Test your solution with all these ages 12, 13, 14, 18, 19, 20. As demonstrated in the last exercise, you are now reaching the stage where, as the code becomes more complicated, testing becomes more important.
   Go to solution 1c.

 


Top of Page


Exercise 1d.
This is an alternative way of solving the problem, using a:-

Nested conditional expression

  1. Starting with the original code
    "T12. Exercise 1 (a)"
    |age|
    age :=24.
    ( (age >= 13) & (age <= 19) ) 
        ifTrue: [ ^'You are a teenager' ]
        ifFalse: [ ^'You are NOT a teenager' ] . 
    		  
  2. Amend the comment to the new exercise number etc.
  3. Amend 'You are NOT a teenager' to 'You are too old to be a teenager'
  4. Place the cursor immediately after the ifFalse: [
  5. And press enter. The result should look like
    "T12. Exercise 1d. Nested conditional expression"
    |age|
    age := 24.
    ( (age >= 13) & (age <= 19) ) 
        ifTrue: [ ^'You are a teenager' ]
        ifFalse: [ 
                            ^'You are too old to be a teenager' ] .	  
    This leaves space for your new nested code.
  6. Look at the last line, then look at the last 2 lines of solution Exercise 1 (c)
  7. The required code is very similar. Remember the code you are about to enter, along with the code that is already ther, will become an expression series, therefore think about the period.
  8. In this space you can enter a conditional expression. Because it is within a block it becomes a nested conditional expression. The condition will be the same as one used in Exercise 1 (c) and depending on that expression either an ifTrue: or ifFalse: structure.

Go to solution 1d

Top of Page

Iteration. (Loops)


Iteration in programming is to repeat a section of code repetitively. The code that does this is commonly called a loop. The loop structures allow you to execute a section of code a number of times and depending on the code this could be from 0 to infinitive.

 

  • Infinitive loops, also known as endless loops should be avoided, they prevent your code from completing.
  • You must write your code to prevent this from happening
  • This is easy when using timesRepeat:, they repeat a set number of times, but be careful with whileTrue: and whileFalse:
  • Tips are given in preventing infinitive loops in the whileTrue: and whileFalse: section below.
  • The computer can run out of memory, resulting in a GC flashing cursor
  • Use the Ctrl q key combination to break out of an infinative loop.
  • Do not use Ctrl Alt Delete combination. You will loose ALL work performed since your last save.
  • That when writing your own methods you can accidentally write an infinative loop without using any of the loop structures.
  • This is covered later in the course.
  • Some TMA questions are carefully written to temp you into making this mistake.

 

Top of Page

timesRepeat:

The message timesRepeat: executes a block of code a specified number of times. The format of the message is:
number timesRepeat: [ block of code to be repeated ]

can be any expression that results in an integer.

 

  • where number can be any expression that results in an integer.
  • block of code to be repeated may be a
    • A single simple message expression
    • A cascading message expression
    • A message expression series.
    • A nested control type structure such as ifTrue:, timesRepeat: whileFalse: etc..
    • A combination of the above

Exercise 2.
Question 8
Examine the Code below. Without copying the expression into the workspace and evaluating, attempt the question that follows the code.

 

| total | 
total := 0. 
4 timesRepeat: [ total := total + 1]. 
total 

a. What does the expression series do ?
b. What is the answer returned ?  
Go to Answers 8.

 


Questions 9.
The following information will aid you answering 8e and f, class is a unary message that can be sent to an object.
Answers with the class of that object. E.g. 'abc' class would answer ByteString

 


In the expression
4 timesRepeat: [ total := total + 1]. 
a. What is the receiver ?
b. What is the message selector?
c. What is the message?
d. What is the argument?
e. What is the class of the receiver?
f. What is the class of the argument?
Go to Answers 9.

 

Now evaluate in the Workspace.
Experiment by altering the number in front of times.
Further experiment by altering the 1 to some other number, to change the increment value.
Confirm your understanding of what this code does by these experiments.

 

Top of Page


Question 10.
Examine the Code below. Without copying the expression into the workspace and evaluating, attempt the question that follows the code.
| aNumber total count | 
aNumber := 4. 
total := 0. 
count := 0. 
aNumber timesRepeat: [ count := count + 1. 
                                       total := total + count ]. 
total.

It is normal to check the results of loops by a physical "step through" the code, checking how variables are changed, and performing any calculations, to ensure that results obtained by execution, are as expected from your "step through". This type of check should find any logical errors in your code.

 

Calculate the answer that will be returned.
You may like to try this now, before reading the following.

 


A brief description of what the code does is in the following table.
If you are still stuck, then the second table shows you how it should be done.

 

| total | 
Declares a variable.
aNumber := 4. 
total := 0. 
count := 0. 
 
Sets the value of the 3 variables.
aNumber timesRepeat: 
     [ count := count + 1. 
       total := total + count ].  
The code in the block is repeated 4 times. Imagine the code is only being executed for 1 repeatCalculate the value of count, then total, You will need to repeat these calculations another 3 times, using the new values of count and total, each time, to calculate the answer.
total 
Answer with the value of total

A table similar to the table below is the ideal way to check results. The table has been been partially filled in, to help you. Complete the 5 remaining cells.
  Value of count Value of total
At start 0 0
Calculate the right hand side to obtain the new value of the variable count :=count + 1 total :=total + count
After repeat 1
  1    := 0 + 1
  1   := 0 + 1
After repeat 2
  2    := 1 + 1
  3   := 1 + 2
After repeat 3    
After repeat 4    
Answer returned is  
Go to Answer 10.

 


Top of Page

Exercise 3. Copy the code from question 10,into the Workspace and evaluate it.

 


If you are having difficulty understanding how the figures were worked out in the above question, you can amend the code as follows in the next 3 exercises.

 

This is a technique that can be used if you are receiving unexpected results from the execution of code. Another useful technique is to step through your code using the debugger.
Exercise 4a. Set the value of aNumber to 1 and evaluate. Note the answer which is the value of total. Check it against the value under total/After repeat 1in the table
Exercise 4b. Repeat the above setting the value of aNumber to 2, then again with 3, and finally 4
Exercise 4c. Repeat the above exercises but amend the last line from total to count.

 

Re-examine the code and note the following points.
  • How the block has a series of 2 expressions.
  • As usual each expression is placed on a separate line.
  • Indentation is used to emphasise that both expressions are within the same block. Note how a different indentation/white space style was used in the table, to that in the original code.
    • Take a note as you read course materials, and books how different authors achieve improved readability of code by using white space and indentation.
    • Be consistent on how you develop your own style.
    • Check with your tutor for any recommended style.
  • Remember periods. The block has a series of 2 expressions which must be separated by a period.

 

Top of Page

whileTrue: and whileFalse:

The general format for a  whileTrue: expression is:
[  a Boolean Condition Block ] 
    whileTrue: [ aBlock of code that is repeatedly executed while the condition remains true ]

The whileTrue: message allows you to repeatedly execute a [aBlock of code] while the preceding [Boolean Conditional Block ] evaluates to true.
  • a Boolean Condition Block can be any expression that results in a value of true or false.
    • It must be enclosed in a block.
  • aBlock of code may be a
    • A single simple message expression
    • A cascading message expression
    • A message expression series.
    • A nested control type structure such as ifTrue:, timesRepeat: whileFalse: etc..
    • A combination of the above

 

The general format for a whileFalse: expression is:
[ aBooleanConditionBlock  ]
     whileFalse:[ aBlock of code that is repeatedly executed while the condition remains false ]

 

Tip. When writing your code care must be taken to avoid producing an endless loop. Note in the following example whileTrue:, how the value of a variable, count used in the [ Boolean Condition Block ], is incremented within the [ Block of code that is repeatedly executed ]. This alteration of the variables value, should eventually reverse the true/false value of the Boolean Condition Block, thus ending the loop. You must be careful that you think carefully whether you increment or decrement the value, often you do both, one in the whileTrue block, and the other in the whileFalse block.

 


Top of Page


Exercise 5a
Compare the 2 sets of code in the table below. The one using timesRepeat: you have just used. The new one using whileTrue: .
Using timesRepeat: Using whileTrue:
| aNumber total count | 
aNumber := 4. 
total := 0. 
count := 0. 
    aNumber timesRepeat: [ count :=count + 1. 
                                           total := total + count ]. 
total.
"T12 Exercise 5b    whileTrue:"
 
| aNumber total count | 
aNumber := 4.
total := 0. 
count := 0. 
[ count < aNumber ] 
    whileTrue: [count := count + 1. 
                       total :=total + count]. 
total. 
Question 11.Does the code using whileTrue: produce the same answer as the code using timesRepeat:
Go To Answer 11.

 

Exercise 5b.
Copy and paste the code to the workspace and evaluate to check the above answer.

 

An expression series that can be written using the message selector timesRepeat: can also be written using the whileTrue: or whileFalse: message selector. and vice versa.
Being able to convert between these constructions shows your understanding of them. Consequently the M206 OU course, usually has the students doing this in a TMA. LB 20 practical 2 has you doing this.

 

Tip. Re study the code in the table above and ensure how they both work.

 


Exercise 5c. optimisation was not possible
Now delete the [ ] from [ aNumber < 4 ] and execute the expression series.
 
Note the exception message and add the Unhandled exception: optimisation was not possible message to your list Note you have a different version of this message for frogs in the list.

 

Replace the brackets. This is another frequently made error.

 


Exercise 6. NonBoolean receiver
Change
[ aNumber < 4 ]
  to
[ aNumber := 4 ]
and execute the expression series.
Note the exception message and add the NonBoolean receiver—proceed for truth message to your list of error messages.

 

Explanation. Writing code that does not answer with true or false will become a NonBoolean receiver. An assignment was used and a Boolean conditional expression was required .

 



The OU (Open University) M206 course uses additional loop methods, with thecollection Classes. These methods are:
do: keysAndValueDo:   detect:   detect:None: and will be covered later.

 


Top of Page

Answers

Answer 1.
An expression series uses . (periods) to separate the expressions.

 

Return to Question 1.

 



Answer 2. A cascading expression uses ; (semi colons) to separate the messages.

 

Return to Question 2.

 



Answer 3.
In a cascading message series only one receiver is written followed by a ; (semicolon). This is followed by successive cascading (consecutive) messages.

 

In an expression series different receivers may be used, each expression being separated by a period. Each expression starts with a receiver.

 

Return to Question 3.

 



Answer 4.
Because the condition is true the caret forces true to be returned as the answer.

 

Return to Question 4.

 



Answer 5.
Both the ifTrue: and the ifFalse: blocks contain carets. Therefore one of these carets must be executed. A caret forces the return of an answer and the termination of the code.

 

Return to Question 5.

 



Answers 6.
No. boolean conditions condition 1 condition 2 answer Tutorial comments
e.g.
 ( (4 < 6) & ('a' > 'c') )
true false false  
a
( (4 < 6) & (21 > 19) )
true true true  
b
( (4 < 6) | (21 > 19) )
true true true  
c
 ( (4 < 6) & (21 < 19) )
true false false  
d
( (4 < 6) | (21  < 19) )
true false true  
e
( (4 > 6) & (21 < 19 ) )
false false false  
f
( (4 > 6) | (21 < 19) )
false false false  
g
( ('c' > 'a') | (21 < 19) )
true false true  
h
 ( ('c' > 'a') & (21 < 19) )
true false false  
i
( ('c' = 'c') | (21  < 19) )
true false true
'c' = 'c'
Strings can be equal.
j
( ('c' == 'c') | (21 < 19) ) 
false false false
'c' == 'c'
Strings are not the same object, beware of this.
k
( (4 < 6) & (21 ~= 19) )
true true true
21 ~= 19
21 is not equal to 19
l
( (4 < 6) & (21 < 19) not ) 
true true true
21 < 19
is false, the not message changes the false to true
Return to Question 6.

 



Answer 7a.
'You are a teenager'

 

Return to Question 7a.

 



Answer 7b.
12, 13, 14, 18, 19, 20. These are the boundary values at both lower and upper limits of the "teenager" range i.e. 13 to 19 inclusive.
Write down these numbers, you will need them in the next exercise.

 

Return to Question 7b.

 



Answer 7c.
'If the input is an integer then the answer is yes, but no for a floating point number. Consider a teenager who is 19 years 3 months, and enters 19.25, an incorrect answer of 'You are NOT a teenager' will be returned.

 

Return to Question 7c.

 


Top of Page


Answer 8.
a.In the expression
4 timesRepeat: [ total :=total + 1]. 
The code, total :=total + 1, is evaluated 4 times, the value of total being incremented by 1 on each repeat.
b. 4

 

Return to Question 8.

 



Answer 9.
a. 4
b. timesRepeat:
c. timesRepeat: [ total :=total + 1]
e. [ total :=total + 1]
f. Evaluate this code in the workspace to find out
4 class. 

b. Evaluate this code in the workspace to find out
| total | 
total := 0. 
4 timesRepeat: [ total := total + 1 ] class. 

Return to Question 9.

 



Answer 10.

 

  Value of count Value of total
At start 0 0
After repeat 1
0 + 1 = 1
0 + 1 = 1
After repeat 2
1 + 1 = 2
1 + 2 = 3
After repeat 3
2 + 1 = 3
3 + 3 = 6
After repeat 4
3 + 1 = 4
6 + 4 = 10
Answer returned is 10
Return to Question 10.

 



Answer 11.
Yes
Return to Question 11.

Top of Page


Exercise Solutions


Solution Exercise 1a
"T12. Exercise 1a and b  Using &,ifTrue:ifFalse:"

Exercise Age Answer As required
Exercise 1a. 24 'You are NOT a teenager' Yes
12 'You are NOT a teenager' Yes
13 'You are a teenager' Yes
14 'You are a teenager' Yes
18 'You are a teenager' Yes
19 'You are NOT a teenager' No
20 'You are NOT a teenager' Yes
The code does not pass when age is 19.

 

Return to exercise 1a

 



Solution Exercise 1b. Correct Error.

 

Insert a period at the end of the ifTrue: [ ^'You are a teenager' ] line
"T12. Exercise 1b.  Using 1 ifTrue:"
|age|
age := 24.
( (age >= 13) & (age < =19) ) 
    ifTrue: [ ^'You are a teenager' ] .
 [^'You are NOT a teenager' ] . 
		  

Return to exercise 1b to continue.

 



Final solution Exercise 1b.
"T12. Exercise 1b.  Using 1 ifTrue:"
|age|
age := 24.
( (age >= 13) & (age <= 19) ) 
    ifTrue: [ ^'You are a teenager' ] .
^'You are NOT a teenager'. 
		  
Note the solution aboveis also required for the next exercise
Another possible solution would have been to place value after the final block
"T12. Exercise 1e.  Using 1 ifTrue:"
|age|
age := 24.
( (age >= 13) & (age < =19) ) 
    ifTrue: [ ^'You are a teenager' ] .
 [^'You are NOT a teenager' ] value . 
		  

Go to next exercise 1c

 


Top of Page


Solution Exercise 1c
"T12. Exercise 1c.  Using 3 ifTrue:'s"
|age|
age := 24.
( (age >= 13) & (age <= 19) ) 
    ifTrue: [ ^'You are a teenager' ] .
(age < 13)
     ifTrue: [ ^'You are too young to be a teenager'] .
(age > 19)
     ifTrue: [ ^'You are too old to be a teenager'] .		  

Return to exercise 1c.

 



Solution Exercise 1d.
"T12. Exercise 1 (d).   Nested conditional expression"
|age|
age := 24.
( (age >= 13) & (age < =19) ) 
    ifTrue: [ ^'You are a teenager' ] 
    ifFalse: [ (age < 13) 
                             ifTrue: [ ^'You are too young to be a teenager' ] .
                               ^'You are too old to be a teenager' ] .	 
Note
  • The nested conditional expression is shown in a red font.
  • That there is nothing special about the code for it to be nested.
  • It is just typed in, at the required positionwithin the ifFalse: block.

Return to exercise 1d.

 



| Previous Tutorial 3. Strings | Next Tutorial 16 Dialog Boxes | Top of Page

 

Copyright © John McGuinn 2001