필터 지우기
필터 지우기

How can i manage a wrong input, whitout restart the my script ?

조회 수: 1 (최근 30일)
Pietro Fiondella
Pietro Fiondella 2022년 6월 22일
댓글: Voss 2022년 6월 22일
I'm writing a script that works whit many input that have to be typed chosing from different possile case.
How can i re-load the question for input if a not allowed choice is typed?
For example consider this script for converting a temperature value from Celsius to Kelvin and inverse (This script works on Matlab but not here!)
clc
T=input ("Set the value of the temperature to convert " );
Unable to run the 'fevalJSON' function because it calls the 'input' function, which is not supported for this product offering.
A=input ('Choose the unit of measure (C for Celsius or K for Kelvin )', 's');
switch A
case 'C'
A= T+273.15
case 'K'
A=T-273.15
end
So, how can i manage a wrong input ?
For example if i digit 'F' instead of 'C or 'K' ant the input A=Input( 'Choose the unit of measure (C for Celsius or K for Kelvin )) i would obtain only an error message.I would like to set the script in such a way that it can automatically restart the from the missed input

채택된 답변

Voss
Voss 2022년 6월 22일
Generally, for this method of gathering user input, you would use a while loop that iterates until the input is valid.
Something like this:
is_valid = false;
while ~is_valid
A = input('Choose the unit of measure (C for Celsius or K for Kelvin )', 's');
if ismember(A,{'C','K'})
is_valid = true;
end
end
Or, equivalently:
while true
A = input('Choose the unit of measure (C for Celsius or K for Kelvin )', 's');
if ismember(A,{'C','K'})
break
end
end
  댓글 수: 2
Pietro Fiondella
Pietro Fiondella 2022년 6월 22일
Thanks a lot.
And what about the first input? I men how to reset the choice for input T T=input ("Set the value of the temperature to convert " ); if i type for example 'S' or something that is not a number?
Voss
Voss 2022년 6월 22일
Try this:
while true
T = str2double(input('Set the value of the temperature to convert ', 's'));
if ~isnan(T)
break
end
end
str2double returns NaN for non-numeric input.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by