2016-02-26 69 views
-1

在下面的代碼中,我檢查第一個字母是否在單詞詞典中,以及單詞的長度是否匹配。如果有,請返回該單詞。否則,返回一個錯誤語句。在Matlab中驗證循環後的顯示結果

words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'}; 

user_letter_input = input('Please enter the first letter of a word: ', 's'); 
user_num_input = input('Please enter how long you would like the word to be: '); 

for i = words 
    if ((i{1}(1) == user_letter_input) && (length(i{1}) == user_num_input)) 
     result = i; 
    else 
     result = 0; 
    end 
end 

if (result == 0) 
    disp('There are no matching words'); 
else 
    disp(['Your new word is: ' result]); 
end 

比較返回i'apple'如果我用於第二輸入所述第一輸入和鍵入5a - 因爲它應該。

然而,在結束的時候我嘗試看看if (result == 0),它不會顯示這個新詞,即使result不爲0

有人能幫助我解決這個問題嗎?

回答

2

每次通過for循環覆蓋resultresult在循環後唯一一次是0,如果words中的最後一個單詞符合您的條件。

我建議將匹配的單詞存儲在單獨的單元格數組中,或者使用布爾數組來指示哪些單詞匹配。在我看來,使用布爾值更好,因爲它佔用更少的內存並且不會重複數據。

words = {'apple', 'banana', 'bee', 'salad', 'corn', 'elephant', 'pterodactyl'}; 

user_letter_input = input('Please enter the first letter of a word: ', 's'); 
user_num_input = input('Please enter how long you would like the word to be: '); 

isMatch = false(size(words)); 

for k = 1:numel(words) 
    word = words{k}; 
    isMatch(k) = word(1) == lower(user_letter_input) && ... 
       numel(word) == user_num_input; 
end 

if ~any(isMatch) 
    disp('There are no matching words'); 
else 
    disp(['Your matching words are:', sprintf(' %s', words{isMatch})]); 
end 

另外,作爲旁註,不要在for循環中使用單元格數組。這導致了很多混亂。也avoid using i as a loop variable

+3

這也將處理多個匹配。 – beaker

1

每當詞典中的單詞不匹配時,您就會覆蓋result。只有最後一個字符匹配,這個工作纔會奏效。你需要改變你的都的result初始化和你的循環:

result = 0; %// assume that no words match 
for i = words 
    if (.... 
     result = 1; %// we found a match... record it 
    end 
    %// no else! If we get no match, result will already be 0 
end 
0

您可以使用標誌來檢測是否找到匹配:

breakflag = 0 
for i = words 
    if ((i{1}(1) == user_letter_input) && (length(i{1}) == user_num_input)) 
     breakflag = 1; 
     break; 
    end 
end 
if (breakflag == 0) 
    disp('There are no matching words'); 
else 
    disp(['Your new word is: ' i]); 
end