I'm creating a function in MatLab that prompts for user input and then displays a message depending on that input. A valid input (an integer from 1-10) will show a message of 'Input recorded' (this is working), and any other input (ie. non integer values, integers outside the range, or text) should display 'Invalid input, try again', and then prompt the user for an input again. This is the function as it stands:
n = 0;
while n == 0
userInput = input('Input an integer from 1 - 10\n');
switch userInput
case {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
disp('Input recorded');
n = 1;
otherwise
disp('Invalid input, try again')
pause(2);
n = 0;
end
end
At the moment, an integer input within the range triggers the confirmation message and breaks out of the while
loop, and any other numeric input triggers my 'Invalid input' message and cycles round again, however, a text input (eg "five") gives me a MatLab error message (image of my console window output included). How do I let the switch statement also accept a text input, to avoid breaking my code if the user types text?
Obviously I'm using a switch
for this at the moment, but I'm sure there might be a better solution with an if, elseif
statement - I'm open to any solution that gets the job done!
five
be a valid input? – Sardar Usama"five"
or'five'
won't return any error butfive
will return an error if you don't have a variable namedfive
in your workspace. – Sardar Usamainput('Input an integer from 1 - 10\n','s');
. But first Robert should answer your question if only numbers like5
are allowed as input or evenfive
. – Tillstr2num
to convert it to an int (as i need to use this value to select an array element)? – Robert Reidstr2num
to convert this to an int afterwards. This makes the various messages display as desired, and ensures the programme only accepts the inputs I want. Thanks for your help guys – Robert Reid