how can i store input characters from user and every time when get new input compare it with already stored values if present already then give error message?

5 ビュー (過去 30 日間)
samia saghir
samia saghir 2017 年 4 月 5 日
回答済み: Jaynik 2024 年 11 月 8 日 7:11
I want to get input characters from user and store it in an array or any other storing elements in matlab, and while loop is running so every time when new character from user is get, it is first compared with the already stored characters, if present in the array already, an error message is generated. This input will be used in switch statement later.

回答 (1 件)

Jaynik
Jaynik 2024 年 11 月 8 日 7:11
Hi Samia,
You can follow two approaches here but the overall steps remain the same. We can initialize an empty data structure to store the characters. Then we obtain the input from the user using the input function. We check the data structure for the input and proceed with the code.
Approach 1: Using while loop and array as suggested by you
storedChars = [];
while true
newChar = input('Enter a character: ', 's');
% Check if the character is already in the array
if any(storedChars == newChar)
disp('Character already entered.');
else
% Add the new character to the array
storedChars = [storedChars, newChar];
switch newChar
% Your code
end
end
end
Approach 2: Using isKey and container.Map
storedChars = containers.Map('KeyType', 'char', 'ValueType', 'logical');
while true
newChar = input('Enter a character: ', 's');
% Check if the character is already in the map
if isKey(storedChars, newChar)
disp('Character already entered.');
else
% Add the new character to the map
storedChars(newChar) = true;
switch newChar
% Your code
end
end
end
Please refer the following documentation to read more about these:
Hope this helps!

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by