2017-11-25 84 views
1

我用matlab創建了一個簡單的密碼程序。如您所知,典型的密碼程序有一個簡單的想法,即如果您錯誤地輸入了三次密碼,程序會向您發送LOCKED!錯誤。 那麼我該如何添加屬性?MATLAB - 屬性

while (x ~= 1111) 
    if (x == password) 
     uiwait(msgbox('Welcome!')); 
     break; 
    else 
     uiwait(errordlg('Try Again!!')); 

     X = inputdlg('Please enter your password'); 
     x = str2double (X{1,1}); 
    end 
end 
uiwait(msgbox('Welcome!')); 
end 
+1

你是相當接近,而不是在而L使用'x' oop,使用一個變量來計數。初始化如下'failed_count = 0',然後運行'while(failed_count

回答

1

你可以把你迭代循環內的計數器:

locked_flag = false 
counter = 0 
while (x ~= 1111) 
    if (x == password) 
     uiwait(msgbox('Welcome!')); 
     break; 
    else 
     uiwait(errordlg('Try Again!!')); 
     counter = counter + 1 
     if (counter == 3) 
      locked_flag = true; 
      %show 'locked' dialog of some kind here 
      break; 
     end 

     X = inputdlg('Please enter your password'); 
     x = str2double (X{1,1}); 
    end 
end 
%can now check if locked_flag true to start unlock logic or other... 

編輯:是的,我只希望你張貼代碼片段,你需要它上面的邏輯,這樣,如果對不起不清楚:

X = inputdlg ('Please enter your password'); 
x = str2double (X {1,1}); 
password = 1111; %whatever 
if (x == password) 
    uiwait(msgbox('Welcome!')); 
else 
    locked_flag = false 
    counter = 1 
    while (x ~= 1111) 
     if (x == password) 
      uiwait(msgbox('Welcome!')); 
      break; 
     else 
      uiwait(errordlg('Try Again!!')); 
      counter = counter + 1 
      if (counter == 3) 
       locked_flag = true; 
       %show 'locked' dialog of some kind here 
       break; 
      end 

      X = inputdlg('Please enter your password'); 
      x = str2double (X{1,1}); 
     end 
    end 
end 
%can now check if locked_flag true to start unlock logic or other... 
2
wrong = 0; 
lock = false; 

% Keeping a char type allows you to use different 
% types of passwords (i.e. alphanumeric). 
password = '1111'; 

% Infinite loop, which allows you to implement full 
% control over the iterations. 
while (true)  
    pass = inputdlg('Please enter your password:'); 

    % If the user pushes the Cancel button, he is not inserting a 
    % wrong password, so no action should be taken towards locking. 
    % If he pushes the Ok button with empty textbox, {''} is 
    % returned, which could be wrong. 
    if (isempty(pass)) 
     continue; 
    end 

    if (strcmp(pass,password)) 
     uiwait(msgbox('Welcome!')); 
     break; 
    else 
     uiwait(errordlg('Try again!')); 
     wrong = wrong + 1; 

     if (wrong == 3) 
      lock = true; 
      break; 
     end 
    end 
end 

if (lock) 
    uiwait(errordlg('Application locked!')); 
    return; 
end 

% Your logic starts here... 
+0

沒關係。但首先爲什麼取消按鈕不起作用?還有一個簡單的問題與您的鎖定屬性:如果您輸入密碼錯誤首先嚐試再次將顯示,然後應用程序鎖定。你知道這個功能並不有趣。我只想顯示一條消息,這是應用程序鎖定! – Joe

+0

當用戶點擊取消按鈕時,這意味着他不想插入密碼......所以,從技術上講,不應該將其視爲錯誤的密碼輸入。最後但並非最不重要的一點是,如果該消息功能沒有意義,只需將其刪除;上帝給了你10個手指,而你只需要其中一個手指去除兩行代碼。 –