I have a few if statements within a while statement, i want them to display different values based on input but they're being skipped over

1 view (last 30 days)
Joshua Stocks
Joshua Stocks on 29 Aug 2020
Answered: Alan Moses on 31 Aug 2020
The following code is a 'game' meant to simulate a ball being thrown at different angles. The ball needs to land on a platform and in turn wil give the player a point.
The two main issues i've had with it are:
  • when "x" is the input it should display thanks for playing (or a similar message)
  • when an angle less than -90 deg and greater than 90 deg is the input it should say invalid input
(here is my code)
%script file
h=figure;
clf(h);
AxesH = axes('NextPlot','add');
disp('Press x to exit')
kwhile = 1;
x = NaN(1);
while theta ~= x
theta = input('Please input angle: ');
if theta >= -90 && theta <= 90
[xf,yf] = HDTask1function_f(theta);
z = rand()*3.5;
pts = 0;
j = z+0.5;
hndl2=plot([z j],[0 0],'LineWidth',5);
hold on
set(gca,'Xlim',[-1 4])
set(gca,'Ylim',[-1 4])
hndl=plot(xf(1),yf(1),'r.','MarkerSize',50);
hold off
for ii=2:length(xf)
drawnow;
pause(0.02)
set(hndl,'XData', xf(ii), 'YData', yf(ii));
pause(0.0025);
if yf(ii:end) < 0
yf(ii:end) = 0;
pause(0.5);
if xf(1,ii) > z && xf(1,ii) < j
pts = pts + 1;
disp('You gained a point');
hold off
end
break
end
end
elseif theta == x
kwhile = kwhile - 1;
disp('Closing Game...')
break
else
disp('<3 Try again. That''s not a valid angle')
continue
end
end %end of while loop
disp('Thanks for Playing')
I've read through a few different online examples but haven't had much luck.
Any help is appreciated, i've been working on this problem all day and my brain is turning into jelly.
  1 Comment
dpb
dpb on 29 Aug 2020
kwhile = 1;
x = NaN(1);
while theta ~= x
...
theta is uniinitialized...
Rearrange the test on theta to reject the unallowed first and then can get rid of all the other else, etc., ...
You're test a variable x instead of a character string 'X'. You'll need to be case-insensitive there, too...

Sign in to comment.

Accepted Answer

Alan Moses
Alan Moses on 31 Aug 2020
Hi Joshua, from your code I understand that you want to type the letter ‘x’ to close the game and display “Thanks for Playing”. To do so, add the following lines of code instead of “x=NaN(1)”:
x = 'x';
theta = 0;
This ensures the variable ‘theta’ is initialized before entering the loop, and terminates the code on entering the letter ‘x’.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!