Re: [Seed7-users] Seed7: RANGE_ERROR
Interpreter and compiler for the Seed7 programming language.
Brought to you by:
thomas_mertes
|
From: Thomas M. <tho...@gm...> - 2021-11-13 18:37:04
|
Hi Duke,
In your code are line breaks in strings. But this
was easy to fix. I can reproduce a RANGE_ERROR when I
enter aa in response to the question
Enter your choice
With aa I get the stack trace:
*** Uncaught exception RANGE_ERROR raised with
{raise RANGE_ERROR }
Stack:
in raise (ref EXCEPTION: anException) at seed7_05.s7i(323)
in (attr type) parse (ref string: stri) at seed7_05.s7i(463)
in readln (inout file: inFile, inout char: aVar) at enable_io.s7i(102)
in readln (inout char: aVar) at enable_io.s7i(170)
in main at tst303.sd7(27)
The function readln() (in enable_io.s7i(102)) has read the string
"aa" and then tries to convert it into a character and this
triggers a RANGE_ERROR (in seed7_05.s7i(463)).
This can be avoided by reading single characters from the KEYBOARD.
See below for the improved example.
A RANGE_ERROR could also be triggered when no number is entered for
readln(temp);
This situation can be recognized with the function
succeeds(readln(temp))
The function succeeds() returns TRUE when no exception occurred.
If an exception occurred it is caught and the function returns
FALSE.
I suggest the following fix:
[code]
$ include "seed7_05.s7i";
include "float.s7i";
include "console.s7i";
include "editline.s7i";
const func float: fahr2cels (in float: temp) is
return 0.5556 * (temp - 32.0);
const func float: cels2fahr (in float: temp) is
return (temp * 1.8) + 32.0;
const proc: main is func
local
var float: temp is 0.0;
var char: choice is ' ';
var text: console is STD_NULL;
begin
OUT := open(CONSOLE);
IN := openEditLine(KEYBOARD, OUT);
clear(STD_CONSOLE);
while choice <> 'q' do
writeln("\nTemperature Conversion Utility");
writeln("------------------------------");
writeln("a - Fahrenheit TO Celsius");
writeln("b - Celsius TO Fahrenheit");
writeln("q - To exit the program");
write("Enter your choice ");
choice := getc(KEYBOARD);
writeln(choice);
case choice of
when {'a'}:
write("Enter a number to convert ");
if succeeds(readln(temp)) then
writeln("\nYour input was " <& temp <& " degrees Fahrenheit!");
write("That's " <& fahr2cels(temp) <& " degrees Celsius!");
else
writeln("\nThis is not a number.");
end if;
write("\nPress any key to continue ..");
readln;
clear(STD_CONSOLE);
when {'b'}:
write("Enter a number to convert ");
if succeeds(readln(temp)) then
writeln("Your input was " <& temp <& " degrees Fahrenheit!");
write("That's " <& cels2fahr(temp) <& " degrees Celsius!");
else
writeln("\nThis is not a number.");
end if;
writeln("\nPress any key to continue ..");
readln;
clear(STD_CONSOLE);
when {'q'}:
writeln("Good bye!");
writeln("\nPress any key to continue ..");
readln;
otherwise:
writeln("Sorry! Invalid choice!");
writeln("\nPress any key to continue ..");
readln;
clear(STD_CONSOLE);
end case;
end while;
end func;
[/code]
Regards Thomas
|