0

正如标题中所说,我无法找到有关如何检查字符串是否PW包含数字的解决方案。PW如果字符串包含数字 ,我如何检查 TP ?

repeat
        writeln;
        writeln('Ok, please enter your future password.');
        writeln('Attention: The Text can only be decoded with the same PW');
        readln(PW);
        pwLength:= Length(PW);
        error:=0;
          for i:= 1 to Length(PW) do begin
            if Input[i] in ['0'..'9'] then begin
            error:=1;
            end;
          end;

           if Length(PW)=0 then
           begin
           error:=1;
           end;

            if Length(PW)>25 then
            begin
            error:=1;
            end;

        if error=1 then
        begin
        writeln('ERROR: Your PW has to contain at least 1character, no numbers and has to be under 25characters long.');
        readln;
        clrscr;
        end;

      until error=0;
4

1 回答 1

2

这就是我编写代码的方式:

var
  PW : String;
  Error : Integer;

const
  PWIsOk = 0;
  PWIsBlank = 1;
  PWTooLong = 2;
  PWContainsDigit = 3;

procedure CheckPassword;
var
  i : Integer;
begin

  writeln;
  writeln('Ok, please enter your future password.');
  writeln('Attention: The Text can only be decoded with the same PW');
  writeln('Your password must be between 1 and 25 characters long and contain no digits.');

  repeat
    error := PWIsOk;
    readln(PW);

    if Length(PW) = 0 then
      Error := PWIsBlank;

    if Error = PWIsOk then begin
      if Length(PW) > 25 then
        Error := PWTooLong;
      if Error = 0 then begin
        for i := 1 to Length(PW) do begin
          if (PW[i] in ['0'..'9']) then begin
            Error := PWContainsDigit;
            Break;
          end;
        end;
      end;
    end;

    case Error of
      PWIsOK : writeln('Password is ok.');
      PWIsBlank : writeln('Password cannot be blank.');
      PWTooLong : writeln('Password is too long.');
      PWContainsDigit : writeln('Password should not contain a digit');
    end; { case}
  until Error = PWIsOk;
  writeln('Done');
end;

这些是需要注意的一些事项:

  • 不要使用相同的错误代码值来表示不同类型的错误。对不同的错误使用相同的值只会使您更难以调试代码,因为您无法分辨哪个测试给出Error了值 1。

  • 定义常量来表示不同类型的错误。这样,读者就不必想知道“3是什么意思”if error = 3 ...

  • 一旦您在密码中检测到一个数字字符,就没有必要检查它后面的字符,因此Break在我的for循环中。

  • 如果我是用户,在程序告诉我我做错了什么之前不被告知规则是什么,我会很生气。事先告诉用户规则是什么。

  • 实际上,最好包含Unclassified一个值为 -1 的附加常量,并通过分配Error给它来开始循环的每次迭代,并在后续步骤中测试Error = Unclassified而不是PWIsOk.

  • 语句是一种case基于序数值选择多个互斥执行路径之一的简洁且易于维护的方式。

于 2016-10-01T11:17:25.760 回答