How to make a loop repeat itself when user typed the wrong letter?
3 次查看(过去 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!