尝试和抓住帕斯卡 [英] Try and Catch In Pascal

查看:141
本文介绍了尝试和抓住帕斯卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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');

这篇关于尝试和抓住帕斯卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆