Clear Filters
Clear Filters

Trouble Getting a Program to Loop

1 view (last 30 days)
Thomas Robertson
Thomas Robertson on 4 Mar 2022
Commented: Sai Teja G on 18 Oct 2023
Hello, I'm currently trying to get some code to Loop But I'm having an issue. As you can see in the code below I'm asking the user if an outputted number matches what it is in the real world. Based on entries they'll get 2 potential options. First if it matches the program will end, next if it doesn't match the program will ask them if they want to enter the real number in again (Y/N) if they answer no the program will end, if they aswer yes I want it to take them back to the beginnning where they are given the option of input a number. Thanks, any help will be appreciated.
str = input('What is the correct value of the lisence plate? ','s');
if str==noPlate
disp('Nice, the value entered matches MatLab');
else
m = input('The entered value does not match MatLab. Would you like to try again? (Y/N)','s');
if m=='N'
disp('The End')
elseif m=='Y'
str = input('What is the correct value of the lisence plate? ','s')
if str==noPlate
disp('Nice, the value entered matches MatLab');
else
m = input('The entered value does not match MatLab. Would you like to try again? (Y/N)','s');
if m=='N'
disp('The End')
elseif m=='Y'
return;
end
end
end
end

Answers (1)

Sai Teja G
Sai Teja G on 18 Oct 2023
Hi Thomas,
I understand that you would like to restart your program when you click 'Y' if it doesn't match the 'noplate' condition.
To accomplish this, I suggest reviewing the following code example that demonstrates how to achieve this functionality:
while true
str = input('What is the correct value of the lisence plate? ','s');
if str==noPlate
disp('Nice, the value entered matches MatLab');
break;
else
m = input('The entered value does not match MatLab. Would you like to try again? (Y/N)','s');
if m=='N'
disp('The End')
break;
elseif m=='Y'
disp('Starting again')
else
displ('Wrong Input, so closing program')
break;
end
end
end
You can adapt the above code snippet to your specific program logic and requirements.
Hope it helps!
  4 Comments
Walter Roberson
Walter Roberson on 18 Oct 2023
I am saying that the code is very likely wrong. It should be using strcmp() or strcmpi() instead of == to compare between items that might well be char vectors -- or if you must use == then make sure that at least one of the parameters is string()
Sai Teja G
Sai Teja G on 18 Oct 2023
Yeah very well explained, thanks. Thomas can write the code accordingly.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!