這個下午爲了改這段代碼改了一下午。糾結的點是:
1 爲什麼break語句不發揮作用,依然死循環
2 break發揮作用了,但只有一次重新輸入機會
3 break一次重新輸入後,gender的輸出依然是第一個錯誤結果,沒有被overwrite
用到的運算步驟必須放到循環裏面,不然break語句無法執行
下面是我自己的代碼,留意其中很重要的計算部分
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
以及重新賦值部分
gender = gender;
尤其是計算部分,如果在循環裏面省略,是無法達到循環的,會一直死循環或者直接break
如果賦值部分不加上去,有可能會導致輸出的結果永遠都是錯的結果
ingender = {'f','m','x'}; % 3 input strings into the cell
s1 = cellstr(ingender); % transfer from cell to string
you.gender = input ('\n\n please enter your gender. (f/m/x)\n\n','s'); % input your gender here
gender = you.gender; % transefer a struct into a string
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
fprintf('\n\n Error! Invalid input!\n\nPlease enter ''f'' for female, ''m'' for male, ''x'' for third sex.\r\n'); % error report
you.gender = input ('\n\n please enter your gender. (f/m/x)\n\n','s'); % input again
gender = you.gender; % transefer a struct into a string % it's necessary to be here
cig2 = isempty(gender); % if it is an empty input
cig1 = strcmp(gender,s1); % compare the input and the right answer
judcig1 = any(cig1); % use any to test is it any "1" in the answer
if (judcig1 == 1) % until the any is "1", end this loop
break; % break the while loop
end
gender = gender; % save the right answer
end % end, when it's the correct answer