Trouble Getting a Program to Loop

조회 수: 1 (최근 30일)
Thomas Robertson
Thomas Robertson 2022년 3월 4일
댓글: Sai Teja G 2023년 10월 18일
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

답변 (1개)

Sai Teja G
Sai Teja G 2023년 10월 18일
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
Walter Roberson
Walter Roberson 2023년 10월 18일
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 2023년 10월 18일
Yeah very well explained, thanks. Thomas can write the code accordingly.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by