10/09/2006

3.7 BREAK指令

break這一個指令常與迴圈while 或for 配合使用,可以自迴圈中跳出至上一層之迴圈,在巢狀迴圈中,break僅能自最內圈跳出圈外,到其對應之end後繼續執行。下面之範例配合while 1…end執行輸入的問答,只有回答N才能利用break跳出迴圈。


% Using break to terminate the execttion.
n=1;
while 1
a=input('Continue? (Y/N) ','s');
A=upper(a);
if isempty(A), A='Y';end
if A=='N', break; end
if A=='Y',
disp('OK, you know how to use BREAK, don''t you?')
disp(['You just try ',int2str(n),' time(s)! Do it again.'])
n=n+1;
else
disp('I don''t understand, please input again.')
end
end


執行之結果:

>>show_break
Continue? (Y/N) d
I don't understand, please input again.
Continue? (Y/N) y
OK, you know how to use BREAK, don't you?
You just try 1 time(s)! Do it again.
Continue? (Y/N) y
OK, you know how to use BREAK, don't you?
You just try 2 time(s)! Do it again.
Continue? (Y/N) n

1 則留言:

Eric Wu 提到...

針對會出現打yyyyy會造成程式依然可以執行的解決方式,可以利用指令 strcmp

EX: if strcmp('Y',A)

確保一定要打對字才行

張貼留言