A.4. Chapter 4

A.4.1. Exercise 1 solution

-- Calculate a triangular number specified by the user

set triangularNumber to missing value
set sum to 0 -- the sum so far

display dialog "Enter your integer" default answer ""

-- make sure an integer was entered
try
    set triangularNumber to text returned of result as integer
end try

if triangularNumber = missing value then
    display dialog "You didn't enter an integer" with icon stop
             buttons {"OK"} default button 1
else
    -- now calculate the requested number

    set sum to (triangularNumber * (triangularNumber + 1) / 2) as integer

    display dialog (sum as string)
end if

A.4.2. Exercise 2 solution

-- Calculate a triangular number specified by the user

set triangularNumber to missing value
set sum to 0 -- the sum so far

display dialog "Enter your integer" default answer ""
-- make sure an integer was entered
try
    set triangularNumber to text returned of result as integer
end try

if triangularNumber = missing value then
    display dialog "You didn't enter an integer" with icon stop
             buttons {"OK"} default button 1
else
    -- now calculate the requested number

    set n to 1

    repeat triangularNumber times
        set sum to sum + n
        set n to n + 1
    end repeat

    display dialog (sum as string)
end if

A.4.3. Exercise 3 solution

-- Calculate a triangular number specified by the user - Version 3

set sum to 0 -- the sum so far set validNumber to false set tries to 1 repeat while tries 3 and not validNumber display dialog "Enter your integer" default answer "" try set textEntered ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.