If you want to quit entire program, type quit again in command window
About While Loops problems
3 views (last 30 days)
Show older comments
Is there anyway to end the program by entering "quit"? As the program keeps going despite displays "Exiting..."
The following is the syntax.
function Individual_Project_Final()
disp('Welcome to Unit Converter interface! ');
disp(' ');
while true
% Accept user input
input_str = input('Enter a number to be converted (or type "quit" to exit program): ', 's');
% Check if the user wants to quit
if strcmp(input_str, 'quit')
disp('Exiting...')
break;
end
% Convert input string to a number
numin = str2double(input_str);
% Check if the input is a valid number
if isnan(numin)
disp('Input invalid. Please enter a whole or decimal number (or type "quit to exit program): ');
else
disp('Input valid. Now please select the unit conversion type (or type "quit to exit program): ');
break;
end
end
% Display the menu for selecting conversion type
disp(' ')
disp('Select conversion type:')
disp('1) Celsius to Fahrenheit')
disp('2) Fahrenheit to Celsius')
disp('3) Centimeters to Inches')
disp('4) Inches to Centimeters')
disp('5) Meters to Foot')
disp('6) Foot to Meters')
disp('7) Kilometers to Miles')
disp('8) Miles to Kilometers')
disp('9) Grams to Ounces')
disp('10) Ounces to Grams')
disp('11) Kilograms to Pounds')
disp('12) Pounds to Kilograms')
disp('13) Tonnes to Tons')
disp('14) Tons to Tonnes')
while true
% Accept user input
input_str = input('Please select conversion type (1-14) (or type "quit" to exit): ', 's');
% Check if the user wants to quit
if strcmp(input_str, 'quit')
disp('Exiting...');
break;
end
% Convert input string to a number
convtype = str2double(input_str);
% Check if input is a valid conversion type
if ~ismember(convtype, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
disp('Conversion type invalid. Please enter a number from 1 to 14 (or type "quit to exit program): ');
else
disp('Input valid. We are now finalizing the resluts based on your input. ');
break;
end
end
% Call the user-defined function from Module 2
[numout,unit] = MyUnitConverter(numin,convtype);
% Output generation
disp(' ');
fprintf('The converted number is: %.2f %s\n', numout, unit);
end
3 Comments
Answers (1)
VBBV
on 19 May 2024
It has already exited, the first while loop, but it's waiting for next input from user ... See the message at bottom left of window in workspace, you need to select or provide a number
9 Comments
VBBV
on 20 May 2024
Try using the code which i modified (that has only one while loop , inner while loop is commented )
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!