How to break a function if the user input is not a number?
Ältere Kommentare anzeigen
I am writing a code to let the user enter the input multiple times using a while loop as shown below:
time=input('Pls enter the time: ');
if isnumeric(time);
while (1)
if time<120;
disp('Stage 1')
time=input('Pls enter the time: ');
elseif time<250;
disp('Stage 2')
time=input('Pls enter the time: ');
elseif time>=250;
disp('Free Flight')
time=input('Pls enter the time: ');
end
end
else
disp('you did not enter a number')
end
I want the code to terminate the program when the user input is not a number. How do I achieve this? The isnumeric does not work in this case.
EDIT:
The basic idea is:
1. Prompt the user to enter a number input so that it returns 'Stage 1' when the input is <120; 'Stage 2' when the input is <250 and 'Stage 3' if the input is >250.
2. After the user entered a valid input, the code will prompt the user to enter another input such that the loop will continue until the user entered an invalid input (i.e. a non-numbered input)
3. The code must break once the user entered a non-number (e.g. hello, abc, #@% etc.) Currently my code above will prompt the user to enter another input after he/she entered a non-number. Which is not what I wanted.
Thanks.
Antworten (2)
time=input('Pls enter the time: ');
if isnumeric(time);
while isnumeric(time)
if time<120;
disp('Stage 1')
elseif time<250;
disp('Stage 2')
elseif time>=250;
disp('Free Flight')
end
time=input('Pls enter the time: ');
end
else
disp('you did not enter a number')
end
Image Analyst
am 27 Okt. 2012
Bearbeitet: Image Analyst
am 27 Okt. 2012
Try this code. It's pretty robust:
defaultValue = '12:34';
titleBar = 'Enter the time';
userPrompt = 'Enter the time';
loopCounter = 1;
failSafeMaxNumberOfLoops = 20; % Fail safe to prevent permanent loops.
while loopCounter < failSafeMaxNumberOfLoops
% Ask user for a number.
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
numericValue = str2double(char(caUserInput));
if ~isnan(numericValue) && ~isempty(numericValue)
% It's all numbers.
break;
end
% If it gets to here, it's not all numbers.
% Optionally warn them. COmment out if you don't want the warning.
warningMessage = sprintf('No!\n%s is not all numbers!', char(caUserInput));
uiwait(warndlg(warningMessage));
% Prevent run away loops
loopCounter = loopCounter + 1;
end
if loopCounter < failSafeMaxNumberOfLoops
message = sprintf('Success!\nThe number is %f', numericValue);
fprintf('The number is %f', message);
msgbox(message);
else
warningMessage = sprintf('I give up.\nApparently you do not want to cooperate!');
uiwait(warndlg(warningMessage));
end
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!