0

到目前为止,我的应用程序已经开始运行,但我现在面临一个问题。仅供参考,我的应用程序是关于获取用户输入(用户输入一些句子,应用程序将查找模棱两可的单词并显示其含义)。

这是我的代码:

final String[] words = {"cowboy", "animal" , "monster", "duck"};
final String[] meanings = { "meaning1", "meaning2", "meaning3", "meaning4" };

private void initControls() {
// TODO Auto-generated method stub
text = (EditText) findViewById (R.id.editText1);

view = (TextView) findViewById (R.id.textView1);

clear = (Button) findViewById (R.id.button2);

clear.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        text.setText("");
        view.setText("");
    }
});

ok = (Button) findViewById (R.id.button1);
ok.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        findAmbiguousWord();
    }   
});
}

private void findAmbiguousWord(){
String string = text.getText().toString();

int index = 0;

for (int i = 0; i < words.length; i++) {
    if (string.toLowerCase().contains(words[i].toLowerCase())) {
        check = true;
        index = i;
    } 
}

view.setText(check ? meanings[index] : "No ambiguous word/s found.");
}

但每当我输入这样的句子时:

 My friend is a cowboy. He is also fond of duck.

它只显示第一个单词,即COWBOY。如何显示其他单词?非常需要和感谢帮助。提前致谢!

4

3 回答 3

0

使用索引列表或在循环中构建输出字符串,而不是仅存储一个索引。

于 2013-08-26T14:02:58.967 回答
0
 StringBuilder ambiguousWords = new StringBuilder();
 for (int i = 0; i < words.length; i++) {
    if (string.toLowerCase().contains(words[i].toLowerCase())) {
        check = true;
        ambiguousWords.append(meanings[i]);
    } 
 }

 view.setText(check ? "No ambiguous word/s found." : ambiguousWords.toString());
于 2013-08-26T14:04:09.673 回答
0

您可以在集合中添加结果,例如 aSet或 a List

private void findAmbiguousWord(){
String string = text.getText().toString();
// create a set to store the results
Set<String> result = new HashSet<String>();
for (int i = 0; i < words.length; i++) {
    if (string.toLowerCase().contains(words[i].toLowerCase())) {
        // ambiguous word, we need its meaning!
        result.add(meanings[i]);
    } 
}

// display the results if there are some
view.setText(result.isEmpty() ? "No ambiguous word/s found." : result.toString());
}
于 2013-08-26T14:12:57.073 回答