What I am trying to do here is to create a program to check whether the input is identical to set password by only using the basics.(if, for, while and such)
The program would need to ask for a password until a correct one is entered.
the code I intended to write was:
key = 'test1234'
x = input('Enter the password: ','s') ;
while strlength(x) ~= 6
if strlength(x) ~= 6
fprintf('\nInput = %s',x)
fprintf('\nPassword is incorrect.')
x = input('Enter the password: ','s')
else strlength(x) == 6
break
end
end
while x ~= key
if x ~= key
fprintf('\nInput = %s',x)
fprintf('\nPassword is incorrect.')
x = input('Enter the password: ','s')
else x == key
break
end
end
fprintf('Password is correct.')
the problem I faced at first was that the use of == function would only work if the key and the input had the same length. Otherwise then it would only pop an error, so I merely made it so that it would check for the length of the password first.
But then after entering 6 length input that is not identical to the desired key, the program would move on to the next criteria and thus pop another error when the next input isn't 6-long.
I am literally new to programming stuff so any help would be appreciated.

 채택된 답변

Sahil Jain
Sahil Jain 2021년 10월 20일
From my understanding of the question, you want to create a basic password checker using basic programms constructs like "if" statements and "for/while" loops. You can make the following changes to your code to make sure it functions.
  1. Use a "string" (double quotes, "test1234") instead of a "character array" (single quotes, 'test1234') for your key. This is because using the "~=" operator with a "character array" returns an array of logical values instead of a scalar.
  2. The length and the value of the entered password need to be checked simultaneously. This can be done using the short-circuit OR operator.
The resulting code would be as follows.
key = "test1234";
x = input('Enter the password: ','s') ;
while strlength(x) ~= strlength(key) || x~=key
fprintf('\nInput = %s',x);
fprintf('\nPassword is incorrect.');
x = input('Enter the password: ','s');
end
fprintf('Password is correct.');
Normally, if "x" and "key" are of different lengths, the "~=" operator would throw an error. However, the short-circuit "||" operator would not evaluate the right side if the left side evaluates to "true" and so no error is thrown in this case.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기

제품

릴리스

R2021a

태그

질문:

2021년 10월 15일

댓글:

2021년 10월 28일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by