How can I loop an if statement

1 回表示 (過去 30 日間)
Tariq Hammoudeh
Tariq Hammoudeh 2022 年 1 月 6 日
回答済み: Daksh 2022 年 12 月 19 日
Im designing a game of battleship and I have the following code to prevent ships from overlapping.
x=zeros(1,36);
startingGrid=input('...')
orientation('..')
if orientation=='h'
while x(3)==1
startingGrid=input('... ');
orientation = input('... ');
end
elseif orientation=='v'
while x(4)==1
startingGrid=input('... ');
orientation = input('... ');
end
end
Now this works fine but whenever I enter one of the letters so for example 'h' (and it overlaps) then try again and enter 'v' it then continues with the program even if it overlaps so how can I make it work every time.
  3 件のコメント
Walter Roberson
Walter Roberson 2022 年 1 月 7 日
Your while loop does not update the variable you are testing to see if the loop should continue.
Tariq Hammoudeh
Tariq Hammoudeh 2022 年 1 月 7 日
編集済み: Tariq Hammoudeh 2022 年 1 月 7 日
@Geoff Hayes For the previous ships i set values of the x array to 1 to represent ships, then my code isnt actually x(3)==1. I check actual numbers but i didnt include any of this here, because that isnt my problem, my problem is just that i want this if statement to loop. So for example after entering an orientation of v and the ship overlaps, so it lets me try again (this works fine) but now if i enter an orientation of h and the ship overlaps, it continues it doesnt let me try again. Beacuse i already passed h and went to v.

サインインしてコメントする。

回答 (1 件)

Daksh
Daksh 2022 年 12 月 19 日
It is my understanding that in your scenario, you want the entire checking loop to restart if orientation is "h" but there is an overlap. I also understand that you don't face this issue with orientation "v" as it comes later in the lines and in the next loop iteration it again checks from "h".
For such a scenario, you can use the "continue" keyword in loop to go through the entire checking process again rather than heading to the next orientation. Kindly refer to the following pseudocode:
while (loop)
take inputs
if orientation=='h'
if overlap happens
continue;
end
end
if orientation=='v'
if overlap happens
continue;
end
end
end
Hope it helps!

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by