尝试和抓住帕斯卡

问题描述:

我正在使用Dev-Pas 1.9.2,并尝试确保程序在输入符号或字母值时不会崩溃。

I'm using Dev-Pas 1.9.2 and am trying to make sure the program doesn't crash when a symbol or a letter value is entered.

我已经谷歌和谷歌搜索,找不到任何关于如何实现这一点的重新生效。

I've googled and googled and can't find any resoruce on how to achieve this.

任何帮助是非常感谢。谢谢!

Any help is greatly appreciated. Thanks!

以下是我要管理输入的代码:

Here is the code I'm trying to manage the input:

 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;


更改代码以接受Char;如果由于某种原因需要整数,请稍后处理转换。

Change your code to accept a Char instead; if you need an integer for some reason, handle the conversion afterward.

这在Delphi中有效;除非你不能使用像 ['1'..'4','9'] 这样的集合,并设置运算符,它应该可以正常工作。

This works in Delphi; unless you can't use sets like ['1'..'4','9'] and set operators, it should work fine.

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;

如果您绝对需要一个要返回的数字,请将返回类型更改回整数(或字节)然后将最后一行更改为:

If you absolutely need a number to be returned, change the return type back to integer (or byte) and then change the final line to:

GetMenuChoice := Ord(OptionChosen) - 48;  

GetMenuChoice := Ord(OptionChosen) - Ord('0');