1
可能有人知道爲什麼這個try catch塊循環不起作用。我希望代碼每當用戶輸入一個字符串而不是一個數字,但它似乎並不想要的時候,就進入catch塊。嘗試catch塊不工作
x = 1;
while x == 1
try
degree = input('Please enter the degree of the polynomial of interest: ');
if degree > 0 && degree <= 4
x = 0;
else
disp('Please Enter a degree from 1 to 4')
end
catch
exit = input('do you wish to exit (Y/N)','s');
if strcmp(exit,'Y')
break
else
disp('Please enter an integer this time')
end
end
end
老實說,我不知道try catch塊是否是實現你想要做的最好的方法。我會說在一個字符串中,使用'str2num'將其轉換爲數字。該函數還會返回一個狀態標誌,告訴您轉換是否成功。然後你可以循環。在這裏檢查:http://www.mathworks.com/help/matlab/ref/str2num.html – pragmatist1
你可以在'try/catch'中調用'input()',不應該在'try/catch'並使用'try/catch'來驗證它是一個整數? (例如使用'mod(degree,1)' – Adriaan