Need help with error checking

조회 수: 2 (최근 30일)
Farouk Omer
Farouk Omer 2021년 1월 18일
편집: James Tursa 2021년 1월 18일
Hello,
I'm trying to get my error handling code (conditions) to work for my code. Basically, what I'm trying to do is when a user to be greeted with an error message if enter a number other than 1 or 2, or if they enter a letter (a non numerical value).
disp('For the following questions, press 1 for yes and 2 for no')
check1 = input (' Does your projectile departure and landing zone share a similar height?: ');
check2 = input (' are you trying to clear a wall?: ');
check3 = input (' Is there an initial velocity?: ') ;
while check1(isnan) || check1~=1 && check1~=2
check1(isnan)
disp ('Error! Input a number (either 1 or 2')
elseif check1~=1 && check1~=2
disp('Error! Only input 1 for yes and 2 for no')
end
end

답변 (1개)

James Tursa
James Tursa 2021년 1월 18일
There are various ways to code this, but keeping the same basic architecture you have chosen you could do this:
while( true )
disp('For the following questions, press 1 for yes and 2 for no')
check1 = input (' Does your projectile departure and landing zone share a similar height?: ');
check2 = input (' are you trying to clear a wall?: ');
check3 = input (' Is there an initial velocity?: ') ;
if( (isequal(check1,1) || isequal(check1,2)) && ...
(isequal(check2,1) || isequal(check2,2)) && ...
(isequal(check3,1) || isequal(check3,2)) )
break;
end
disp('Error! Only input 1 for yes and 2 for no')
end
This will run in a loop until the checks pass.
  댓글 수: 2
Farouk Omer
Farouk Omer 2021년 1월 18일
The project requires us only to make use of if,while,else,elseif conditions conditions and for/while loops. Is there another way where it could be done that way (similar to the way I wrote it)? Thanks for the input.
James Tursa
James Tursa 2021년 1월 18일
편집: James Tursa 2021년 1월 18일
My suggestion uses only the while and if controls. This seems to match your requirements.

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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by