0

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....

4

2 回答 2

3

那是因为你的逻辑是错误的

(str ~= 'P') || (str ~= 'F') || (str ~= 'V') || (str ~= 'G')

总是正确的,因为 str 总是与 P、F、V 或 G 不同。它不能与您所要求的所有这些相同。

它应该是

str ~= 'P' && str ~= 'F' && str ~= 'V' && str ~= 'G'

或者

~(str == 'P' || str == 'F' || str == 'V' || str == 'G')

或在理智的matlab中

~any('PFVG' == str)
于 2013-04-10T12:41:03.057 回答
1

如何使用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
于 2013-04-10T12:43:51.113 回答