Output problem for If - statement in For - Loop
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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?
0 Commenti
Risposta accettata
Voss
il 20 Apr 2024
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
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!