像自动更正这样的代码需要 Java 帮助

标签 java android matcher autocorrect

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

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);

            }
        }});

最佳答案

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

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

如下所示,我为您做了一些清理并使用 Map 接口(interface)实现您的逻辑。错误的值必须是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());

关于像自动更正这样的代码需要 Java 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35167195/

相关文章:

java - GlassFish 4 (EJB3) - 无状态 bean 生命周期

java - 无法通过在 Grails 中使用 REST Web 服务来下载 pdf 文件

Java:滚动时填充文本区域(动态更新)

android - Google Maps v2 设置缩放级别

android - 获取 Facebook 好友列表 - Android

Java 正则表达式匹配器

java - 简单的Java正则表达式匹配失败

java - RenderScript 模糊覆盖原始位图

android - 如何从 Google API Android v2 中保留标记?

python - Spacy Matcher - 只匹配最长的字符串