我正在使用 Dev-Pas 1.9.2 并试图确保在输入符号或字母值时程序不会崩溃。
我已经在谷歌上搜索和搜索,但找不到关于如何实现这一目标的任何资源。
任何帮助是极大的赞赏。谢谢!
这是我试图管理输入的代码:
Function GetMenuChoice : Integer;
Var
OptionChosen : Integer;
Begin
Write('Please enter your choice: ');
Readln(OptionChosen);
If (OptionChosen < 1) Or ((OptionChosen > 4) And (OptionChosen <> 9))
Then
Begin
Writeln;
Writeln('That was not one of the allowed options. Please try again: ');
End;
GetMenuChoice := OptionChosen;
End;
最佳答案
更改您的代码以接受一个字符;如果出于某种原因需要整数,请在之后处理转换。
这在 Delphi 中有效;除非你不能使用像 ['1'..'4','9']
这样的集合并设置运算符,它应该可以正常工作。
Function GetMenuChoice : Char;
Var
OptionChosen : Char;
Begin
repeat
Write('Please enter your choice: ');
Readln(OptionChosen);
If not (OptionChosen in ['1'..'4', '9'])
Then
Begin
Writeln;
Writeln('That was not one of the allowed options. Please try again: ');
End;
until OptionChosen in ['1'..'4', '9'];
GetMenuChoice := OptionChosen;
End;
如果您绝对需要返回一个数字,请将返回类型改回整数(或字节),然后将最后一行更改为:
GetMenuChoice := Ord(OptionChosen) - 48;
或者
GetMenuChoice := Ord(OptionChosen) - Ord('0');
关于error-handling - 尝试并捕获帕斯卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6076227/