Try and Catch In Pascal

2019-02-23 09:14发布

问题:

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;

回答1:

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

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;  

or

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


回答2:

(in addition to Ken White's)

  1. I think one can use READ for a char typed variable, and save the user to type enter.

  2. But I would go for a string typed version and use VAL.

    • It is something more encoding agnostic, and
    • the principle extends beyond value 9.
    • requires an enter though, and heavy input will mess up your screen.

For the latter there are other methods (e.g. using unit Crt or Video), but that probably goes beyond the scope of the assignment



回答3:

Do you really want to accept exactly four different possible inputs? (The numbers 1, 2, 3, 4, and 9) That's what you're asking for at the moment.

Note: even with a change like the first answerer suggested, your code has a major problem. What happens if a 5 or Q is given ... you complain, AND THEN EXIT THE ROUTINE.

In the original code, if I enter a 100, you'll print the "That was not allowed"... and then return 100 to the caller.

Hint: loop.

Hint 2: ensure you don't loop forever

BTW, NEVER do: ord (some character) - 48 instead, always use: ord (some character) - ord ('0')

Why? Two obvious reasons:

  1. readability. What's 48?

  2. correctness. If you're compiled on a non-ASCII system, 48 may not be the character code for 0.

Stan