比较字符串时可以创建OR语句吗?

时间:2013-05-15 23:55:30

标签: java string if-statement

我的代码是:

import java.util.Scanner;

class mainClass {
    public static void main (String [] args) {          
        secondaryClass SCO = new secondaryClass();          
        Scanner scanner = new Scanner(System.in);           
        String randomtext = scanner.nextLine();    
        if(randomtext.equals("What is the time"))
        {
            SCO.giveTime();               
        }
        else if (randomtext.equals("Whats the time"))
        {       
            SCO.giveTime();             
        }
    }       
}

我想知道我是否可以用以下内容替换if else语句:

import java.util.Scanner;

class mainClass {
    public static void main (String [] args) {  
        secondaryClass SCO = new secondaryClass();      
        Scanner scanner = new Scanner(System.in);       
        String randomtext = scanner.nextLine();
        if(randomtext.equals("What is the time" || "Whats the time"))
        {
            SCO.giveTime();
        }       
    }
}

顺便说一句,SCO是我的第二课的对象,它完美地输出时间。

6 个答案:

答案 0 :(得分:4)

您可以使用正则表达式进行一次比较,但它只会将OR从java移动到正则表达式:

if (randomtext.matches("(What is the time)|(Whats the time)"))

虽然你可以更简洁地表达它:

if (randomtext.matches("What(s| is) the time"))

甚至可以选择撇号和/或问号:

if (randomtext.matches("What('?s| is) the time\\??"))

答案 1 :(得分:3)

你需要这样说:

if (randomtext.equals("What is the time") || randomtext.equals("Whats the time"))

答案 2 :(得分:1)

您正确使用||逻辑或运算符,但您使用它的方式有误。从第一个示例中的ifelse if中获取每个特定条件,并将||放在它们之间只需一个if而不需要else if

答案 3 :(得分:1)

最明显的方法是:

if(randomtext.equals("What is the time") || randomtext.equals("Whats the time"))
{
      SCO.giveTime();
}

但是从JDK 7开始,您可以使用switch语句:

switch (randomtext) {
    case "What is the time":
    case "Whats the time":
        SCO.giveTime();
        break;
}

答案 4 :(得分:1)

另一种看法:

import java.util.Scanner;

class mainClass {
    public static void main (String [] args) {
        secondaryClass SCO = new secondaryClass();

        Scanner scanner = new Scanner(System.in);

        String randomtext = scanner.nextLine();

        List<String> stringsToCheck = new ArrayList<String>();
        stringsToCheck.add("What is the time");
        stringsToCheck.add("Whats the time");

        if (stringsToCheck.contains(randomtext)) {
              SCO.giveTime();
        }       
    }
}   

答案 5 :(得分:-1)

假设条件语句中只有两个可能的选项,则可以使用此

randomtext = Condition1 ? doesThis() : doesThat();

P.S。我不会做“案件”。在这种情况下,它并不重要,因为它只有两个选项,但是当你使用案例时,每个案例行将根据条件“TRUE”单独检查,这可能需要很长时间才能完成长程序。