while Loop on user input

2 vues (au cours des 30 derniers jours)
fushen Lee
fushen Lee le 3 Fév 2021
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

Réponses (1)

ag
ag le 12 Mar 2025
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!

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by