Aman Saraf
Aman Saraf

Reputation: 607

Prompt User to enter value again in Matlab

I need a user to input 1 or 2. If not 1 or 2, I want user to enter the value of b again. How can I prompt user to enter the value again if not 1 or 2?

Matlab Code

b = input('Choose the device Press 1 for the first device Press 2 for the 
second device');

switch b

case 1
    disp ('Good')
case 2 
    disp ('Good')
otherwise
    Disp('Wrong choice')
  % (I want user to enter the value of b again . It must be 1 or 2 . How to prompt user to enter the value again ? )        
end

Upvotes: 2

Views: 609

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

I would do something like this:

success = false;
while ~success
    b = input('Choose the device Press 1 for the first device Press 2 for the second device');
    switch b
        case 1
            disp ('Good')
            success = true;
        case 2 
            disp ('Good')
            success = true;
        otherwise
            disp('Wrong choice')
            success = false;
    end
end

In this way you have a loop that continues until the variable success becomes true. If the user enters 1 or 2, it becomes true and the loop exits, otherwise it remains false and goes around the loop again.

Upvotes: 4

Related Questions