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:
- input - https://www.mathworks.com/help/matlab/ref/input.html
- strcmpi - https://www.mathworks.com/help/matlab/ref/strcmpi.html
- while loop - https://www.mathworks.com/help/ecoder/ug/while-loop.html
Hope this helps!