Handle error from input

조회 수: 3 (최근 30일)
Muhammad Sultan Zaki Rizaldy
Muhammad Sultan Zaki Rizaldy 2021년 10월 24일
답변: Ive J 2021년 10월 24일
I have two input from user, the first input is receive name(string), the second is receive calorie(numeric). But sometimes user input a string to the second input, how i can handle the error from default matlab using my customize error message?
nama = input("Input your name: ", 's');
kal = input("Input your maximum calories: ");
if(~isnumeric(kal))
msg = "Error: Please input numeric to calorie");
error(msg);
end
But the result is always default error message from matlab,
Error using input
Unrecognized function or variable 'q'.
Error in main (line 5)
kal = input("Input your maximum calories: ");
Error in app (line 5)
[nama, kal] = main();

답변 (1개)

Ive J
Ive J 2021년 10월 24일
AFIK input doesn't let you control the error behavior. The better approach would be to return it as a string, and validate it:
kal = input("Input your maximum calories: ", "s");
kal = double(string(kal)); % str -> double
if isnan(kal)
error("Error: the value must be of numeric data type!")
end

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by