while Loop on user input

12 次查看(过去 30 天)
fushen Lee
fushen Lee 2021-2-3
编辑: Walter Roberson 2025-3-12,18:11
Hi i am new for Matlab may i know to create a loop function when user input ?
purchase type L for Laptop and D for Desktop
if user input L or D
will disply Laptop or ether Desktop depent on input
if user input invild data will show invild input and loop to puchase type ask for input puchase type again
purchase_type = input("Enter type of purchase (L for Laptop / D for Desktop): ", "s");
if purchase_type >= ("L for laptop , D for Desktop ");
else
purchase_type = "invalid";
end
if strcmp(purchase_type, "invalid") == false
fprintf("Invalid type of puchase_type! %s\n");
else
fprintf input = ("Enter type of purchase (L for Laptop / D for Desktop) %s\n"});
end

回答(1 个)

ag
ag 2025-3-12,18:01
Hi Fushen,
Below is a modified version of your code:
% Initialize the purchase_type variable
purchase_type = '';
% Loop until a valid input is received
while true
% Prompt for user input
purchase_type = input("Enter type of purchase (L for Laptop / D for Desktop): ", "s");
% Check if the input is valid
if strcmpi(purchase_type, 'L')
fprintf("You selected: Laptop\n");
break; % Exit the loop
% similar logic for other case
else
fprintf("Invalid input!");
end
end
For more details, please refer to the following MathWorks documentations:
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by