Creating a password checker using basic programming

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 日

0 投票

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.

1 件のコメント

윤은 지
윤은 지 2021 年 10 月 28 日
Hi, sorry for the late reply. Thanks for the help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB Coder についてさらに検索

製品

リリース

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