Output problem for If - statement in For - Loop

This is a part of my code:
answerCoordinates = [238, 285; 152, 130; 108, 565; 489, 557; 238, 287; 289, 557; 530, 335];
for i = 1:size(answerCoordinates, 1)
answerX = answerCoordinates(i, 1);
answerY = answerCoordinates(i, 2);
if x >= (answerX - 25) && x <= (answerX + 25) && y >= (answerY - 25) && y <= (answerY + 25)
fprintf("You have found a new spot! \n");
fprintf("Current Progress: %d/5 \n",currentLoop)
currentLoop = currentLoop + 1
% else
% stopThegame = stopThegame + 1
% else
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,'Type', 'Rectangle');
% delete(rect);
% currentLoop = 1
end
% if stopThegame ~= 7
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,'Type', 'Rectangle');
% delete(rect);
% currentLoop = 1
% end
end
The for loop will iterate 7 times, considering there are only 7 answers. The if-statement aims to identify whether the user's entered coordinate matches one of the answer coordinates. I'm having difficulty outputting the value when the user's coordinate doesn't match any of the answer coordinates. The section involving '%' is my attempt to address this issue, but it hasn't been successful so far.
How can I solve this problem?

 채택된 답변

Voss
Voss 2024년 4월 20일

0 개 추천

The difficulty, as you've found, is that to determine that the user's input does not match any of the answers, you have to check the user's input against all answers. Therefore, you won't know that it doesn't match any until after the loop.
You can create a variable that tells you whether the user's input matched an answer, initially false, set it to true when a matching answer is found, and check if it's false after the loop - indicating that no answer matched - and do what you need to do in that case. Maybe something like this:
good_answer = false;
answerCoordinates = [238, 285; 152, 130; 108, 565; 489, 557; 238, 287; 289, 557; 530, 335];
for i = 1:size(answerCoordinates, 1)
answerX = answerCoordinates(i, 1);
answerY = answerCoordinates(i, 2);
if x >= (answerX - 25) && x <= (answerX + 25) && y >= (answerY - 25) && y <= (answerY + 25)
fprintf("You have found a new spot! \n");
fprintf("Current Progress: %d/5 \n",currentLoop)
currentLoop = currentLoop + 1
good_answer = true;
break % exit the loop - no need to check other answers
end
end
if ~good_answer
fprintf("Ops!Wrong Spot!Start Again!")
rect = findall(gcf,'Type', 'Rectangle');
delete(rect);
currentLoop = 1
end

댓글 수: 2

Wujiacheng
Wujiacheng 2024년 4월 21일
That solve the problem! Thank you so much! Have a great day!
Voss
Voss 2024년 4월 21일
You're welcome!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

제품

릴리스

R2023b

질문:

2024년 4월 20일

댓글:

2024년 4월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by