I would like to display errors in case a user enters a number less or equal to 0.how can i put it? thanks
Problem:Write a script areaMenu that will print a list consisting of “cylinder”, “circle”, and “rectangle”. It prompts the user to choose one, and then prompts the user for the appropriate quantities (e.g., the radius of the circle) and then prints its area. If the user enters an invalid choice, the script simply prints an error message. The script should use a nested if-else statement to accomplish this. (units are assumed to be inches) source:attawy matlab introduction and problem solving in matlab chapter 4 problem 27
%This script asks the user for a type of area
% and prints which type of area to calculate using if-else
%units are assumed to inches
mychoice = menu('choose an area','cylinder', 'cycle','rectangle');
if mychoice == 1
disp('your choice is a cylinder')
rad=input('Enter the radius of cylinder:');
len=input('Enter the length of cylinde:');
%the cylinder is closed both sides
%print area.
areacylinder=2*pi*rad*rad+pi*rad*len;
fprintf('The area of cylinder is %.2f\n',areacylinder)
elseif mychoice == 2
disp('your choice is a cycle')
rad=input('Enter the radius of a circle:');
areacycle=pi*rad*rad;
%print area
fprintf('The area of a cycle is %.2f\n',areacycle)
elseif mychoice == 3
disp('your choice is a rectangle')
wid=input('Enter the width of rectangle:');
len=input('Enter the length of rectangle:');
arearectangle=2*(wid+len);
%print area.
fprintf('The area of a rectangle is %.2f\n',arearectangle)
end
There are several ways you can achieve this. The simplest would probably be to add something like
after the user inputs the lengths (of course using
rad<=0orwid<=0 || len<=0instead if the user chooses circle or rectangle respectively). This will exit the script if the input is negative. If you want to give the user a chance to input a positive number instead of starting over, you could do something likefor each of the input variables.