【问题标题】:Java help needed for a code like Autocorrect自动更正之类的代码需要 Java 帮助
【发布时间】:2016-02-03 01:58:44
【问题描述】:

我正在编写一个与自动更正相反的程序。逻辑是用户输入一个句子,当按下按钮时,应该显示用户输入的句子的语法反义词。我大致能够得到代码。我使用了匹配器逻辑。但我无法获得所需的输出。我将代码与这个问题联系起来。谁能帮帮我?

imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = editText.getText().toString();
                String store = input;
                String store1 [] = store.split(" ");
                String correct[] = {"is","shall","this","can","will"};
                String wrong [] = {"was","should","that","could","would"};
                String output = "";
                for (int i=0;i<store1.length;i++) {
                    for(int j=0;j<correct.length;j++){
                        if(store1[i].matches(correct[j])) {
                            output = input.replace(store1[i], wrong[j]);


                            //store1[i] = wrong[j];
                        }
                        else
                        {
                            input.replace(store1[i], store1[i]);
                            //store1[i] = store1[i];
                        }

                    }
                mTextView.setText(output);

            }
        }});

【问题讨论】:

  • 尝试使用equalsIgnoreCase 而不是matches。因为matches 是正则表达式模式

标签: java android matcher autocorrect


【解决方案1】:

通过查看您的代码,我发现了一些冗余未使用的变量。如下所示。

 String store = input;
 String store1 [] = store.split(" ");

如下所示,我为您做了一些清理工作,并使用 Map 接口实现了您的逻辑。错误的值必须是地图的 Key,以便我们可以使用 Map.containKeys(word) 轻松确定单词是错误的值。如果找到键,那么我们将输出变量与正确的单词连接起来。

    String input = editText.getText().toString().split(" ");

    Map<String, String> pairs = new HashMap<>();
    pairs.put("is", "was");
    pairs.put("shall", "should");
    pairs.put("this", "that");
    pairs.put("can", "could");
    pairs.put("will", "would");

    String output = "";

    for (String word : input) {
        if (pairs.containsKey(word)) {
            output = output + pairs.get(word) + " ";
        } else {
            output = output + word + " ";
        }
    }

    mTextView.setText(output.trim());

【讨论】:

  • 谢谢:) 但这就是我得到的:
  • 示例:输入:这太棒了,输出:这太棒了。我希望输出是:这太棒了
  • @R.ven 如果输入是这太棒了?输出将是这太棒了?我说的对吗?
猜你喜欢
  • 2018-02-07
  • 2011-02-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 2013-03-24
  • 2018-01-27
  • 1970-01-01
相关资源
最近更新 更多