How to make a loop repeat itself when user typed the wrong letter?
2 ビュー (過去 30 日間)
古いコメントを表示
Hi all,
I created a loop where the user need to state whether the already stated filepath in the script is correct. If not they can select the desired filepath. I'm also trying to make the user type 'y' or 'n' and if they have typed anything else i want the loop to repeat itself unitil the correct letter is typed. But i am struggling to do the last part.
This is what the coding looks like right now:
p='E:\...';
fprintf('Data to be analysed is located in: \n');
fprintf('<strong>%s\n</strong>', p)
x=input('\nIs the file path correct? Y/N: ','s');
if strcmpi(x, 'Y');
disp('Thank you, the file path has been saved.')
...
elseif strcmpi(x, 'N');
disp('Please select the required file path.')
p=uigetdir(path);
fprintf('Thank you, the new file path has been saved as: \n');
fprintf('<strong>%s\n</strong>', p);
...
else strcmpi(x,'');
disp('Please type "Y" or "N"');
x=input('Is the file path correct? Y/N: ','s');
...
end
As you can see the last part, if the user type the wrong letter twice it will stop the loop but i want it to repeat until the correct letter is typed.
Any suggestion on how i can do so?
Thank you :)
0 件のコメント
採用された回答
Antoni Garcia-Herreros
2023 年 3 月 20 日
Hello S C,
p='E:\...';
fprintf('Data to be analysed is located in: \n');
fprintf('<strong>%s\n</strong>', p)
x=input('\nIs the file path correct? Y/N: ','s');
while ~strcmpi(x, 'Y') && ~strcmpi(x, 'N') ; % It will only exit this loop when Y or N are pressed
disp('Please type "Y" or "N"');
x=input('Is the file path correct? Y/N: ','s');
end
if strcmpi(x, 'Y');
disp('Thank you, the file path has been saved.')
elseif strcmpi(x, 'N');
disp('Please select the required file path.')
p=uigetdir(path);
fprintf('Thank you, the new file path has been saved as: \n');
fprintf('<strong>%s\n</strong>', p);
end
Hope this helps!
その他の回答 (1 件)
Abb
2023 年 3 月 20 日
編集済み: Abb
2023 年 3 月 20 日
You can achieve this by putting the code block inside a while loop and using a flag variable to control the loop. Here's an example:
p='E:\...';
fprintf('Data to be analysed is located in: \n');
fprintf('<strong>%s\n</strong>', p)
flag = false;
while ~flag
x=input('\nIs the file path correct? Y/N: ','s');
if strcmpi(x, 'Y');
disp('Thank you, the file path has been saved.')
flag = true;
elseif strcmpi(x, 'N');
disp('Please select the required file path.')
p=uigetdir(path);
fprintf('Thank you, the new file path has been saved as: \n');
fprintf('<strong>%s\n</strong>', p);
else
disp('Please type "Y" or "N"');
end
end
This will continue to prompt the user for input until they enter either "Y" or "N". The flag variable is initially set to false, and the loop will continue to run until it is set to true when the user enters "Y".
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!