Reputation: 3336
I'm writing a function in Matlab that prompts the user to select an Instrument (.wav file) to be read in using the wavread
function.
I'm trying to include some sort of error handling/deal with incorrect inputs from the user.
So far my function looks like this:
prompt = 'Select Instrument, Piano: [P], Fork: [F], Violin: [V], Gameboy: [G]';
str = input(prompt,'s');
if isempty(str)
str = 't';
end
while(str ~= 'P') || (str ~= 'F') || (str ~= 'V') || (str ~= 'G')
prompt = 'Invalid Selection! Choose, Piano: [P], Fork: [F], Violin: [V], Gameboy: [G]';
str = input(prompt,'s');
if isempty(str)
str = 't';
elseif (str == 'P') || (str == 'F') || (str == 'V') || (str == 'G')
break
end
end
If prompted during the while loop, it successfully prompts the user and reads in the .wav
, but if the user presses P
,F
,V
, or G
on the first prompt, the while loop is still used and "Invalid Sel... "
is still displayed...
I'm not sure how I should be implementing this....
Upvotes: 0
Views: 2933
Reputation: 191
how about using strcmp
?
str = input(prompt,'s');
if isempty(str)
str = 't';
end
while ~any(strcmp(str,{'P' 'F' 'V' 'G'})) %|| (str ~= 'F') || (str ~= 'V') || (str ~= 'G')
prompt = 'Invalid Selection! Choose, Piano: [P], Fork: [F], Violin: [V], Gameboy: [G]';
str = input(prompt,'s');
if isempty(str)
str = 't';
elseif (str == 'P') || (str == 'F') || (str == 'V') || (str == 'G')
break
end
end
Upvotes: 1
Reputation: 13279
that's because you logic is wrong
(str ~= 'P') || (str ~= 'F') || (str ~= 'V') || (str ~= 'G')
is always true as str is always going to be different from either P, F, V or G. It can't be the same as all of them which is what you are asking.
It should be
str ~= 'P' && str ~= 'F' && str ~= 'V' && str ~= 'G'
or
~(str == 'P' || str == 'F' || str == 'V' || str == 'G')
or in sane matlab
~any('PFVG' == str)
Upvotes: 3