Computer Science Canada

Problems Error Trapping Integers

Author:  olafsonemily [ Sun Jun 17, 2012 9:53 pm ]
Post subject:  Problems Error Trapping Integers

Hello! I have a grade 9 Turing exam approaching, and I noticed a problem that would pop up occasionally when I was error trapping integers. If anyone can tell me how to error trap for integers using either strint or strintok without making my locx variable a string, it would be much appreciated. Thanks in advance!



I've tried using strint and strintok, but it seems that the only way I can error trap for integers is by turning it into a string like so:

Turing:

var locx : string

get locx
if strintok (locx) then
else
    put "Sorry, please enter an integer."
end if


And if I do that, I cannot error trap for if the integer that was input is outside a certain range, as it must be an integer, not a string. Anything helps, my exam is on the 20th.

Here's my code so far, you'll notice an error with "intstr".


Turing:


var locx : int

proc userInput
    var key : string (1)
    locate (5, 1)
    put "Please enter the location of the star on the x-axis: " ..
    get locx
    if locx > 640 or locx < 0 then
        put "sorry, that is not within the limit of the screen. Please enter a number between 0 and 640."
        put "Press any key to try again " ..
        getch (key)
        userInput
    end if
    if intstr (locx) then
        put "Sorry, please enter an integer."
    else
    end if
end userInput

userInput




Using Turing 4.1

Author:  Raknarg [ Sun Jun 17, 2012 10:06 pm ]
Post subject:  RE:Problems Error Trapping Integers

intstr does not result a boolean, it results a string from an integer. That's what strintok is for. If strintok (input) results a false, then it means you cant convert the string to an integer. If it's true, then you can. Use that knowledge for errorchecking.

Author:  Dreadnought [ Sun Jun 17, 2012 11:23 pm ]
Post subject:  Re: Problems Error Trapping Integers

You can check if the string can be converted to an integer. Then convert it and check if its within the bounds (if it can be converted).

You'll need to use a nested if statement, but it shouldn't be too tough.


: