【问题标题】:If statement in Android Studio - Proceed if just one word in a sentence matchesAndroid Studio 中的 If 语句 - 如果句子中只有一个单词匹配则继续
【发布时间】:2016-08-29 05:09:14
【问题描述】:

我正在尝试创建一个应用程序来检查在 EditText 字段中输入的语句的条件。目前,我已经写了如果输入的单词是不区分大小写的“下一个”,然后按“博客”按钮进入下一个屏幕。

我的问题是如何编写“if”语句,以便如果在 EditText 字段中输入了一个短语,并且该短语的任何部分都包含“next”这个词,然后按“”进入下一页博客按钮?例如,如果输入短语“请转到下一页”,则“if”语句应该识别出不区分大小写的单词“next”,因此允许您通过按进入下一页“博客”按钮。

下面是需要修改的部分相关代码的sn-p:

 public void onButtonClick(View v) {
    if (v.getId() == R.id.Blogin) {
        String str = a.getText().toString();


        //Go to the next 'Display' window or activity if the person enters the correct username which is not case sensitive
        if (str.equalsIgnoreCase("next")) {
            Intent userintent = new Intent(MainActivity.this, Display.class);
            startActivity(userintent);
        } else {
            Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
        }
    }
}

【问题讨论】:

  • if (str.toLowerCase().contains("next"))
  • @DanielNugent 的回答是正确的。
  • 这两种方法都很好用,但 Daniel 你的方法最容易实现

标签: android listview android-studio android-intent android-edittext


【解决方案1】:

您真正需要做的就是将contains() 方法与toLowerCase() 方法结合使用:

    if (str.toLowerCase().contains("next")) {
        Intent userintent = new Intent(MainActivity.this, Display.class);
        startActivity(userintent);
    } else {
        Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
    }

如需更深入的信息,请参阅此处:String contains - ignore case

【讨论】:

    【解决方案2】:

    你可以使用java.lang.String.contains(),像这样:

    if (str.contains("next")||str.contains("Next") {
        Intent userintent = new Intent(MainActivity.this, Display.class);
        startActivity(userintent);
    } else {
        Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
    }
    

    【讨论】:

    • “neXt”或“nexT”或“nExT”呢?
    • @DanielNugent 好点,你是对的。我会更新答案。
    • @DanielNugent 转念一想,我觉得我在偷你的答案。你应该写下你自己的答案:)
    • 我会等到@DanielNugent 发布答案然后接受它
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2016-07-30
    • 2013-01-23
    • 2020-10-04
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多