2015-09-05 37 views
-5

我不知道该怎么解释这个问题,但希望这将让你明白有人能告诉我一个简单的方法来比较字符串

我知道这个代码不工作

a = "hello"; 
    if (a.equals("hello" || "greetings")){ 
     //Execute code 
    } 

有一个简单的方法来做到这一点没有错误

我能做到这一点,但是这意味着我需要重复两个

a = "hello"; 

    if (a.equals("hello")){ 
     //Do code 
    } 
    if (a.equals("greetings")){ 
     //Execute code 
    } 
01码

这是我目前的代码,但它不是我想要的。 我想要它做的是,如果例如topic = "Whats the date";我希望它执行代码,因为它包含日期,我无法找到一种方法来检查它是否包含日期,所以||。工作

 scanner = new Scanner(System.in); 
     String topic = scanner.nextLine(); 
     topic = topic.toLowerCase(); 

    if (topic.equals("time") || topic.equals("date")){ 
     System.out.println("The time is " + Calendar.getInstance().getTime()); 
    } 
+1

有很多的例子,检查链接。 [见.equals()] [1] [1]:http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – ohadsas

+1

@ GurfX你应该真的阅读更多的Java编程。您发布的代码包含几个语法错误。 –

+0

@MCEmperor我知道我只使用该代码,所以你可以理解我的问题。我知道代码没有工作 – Albert

回答

-1

我发现一个回答我的问题一些试验后,很抱歉的混乱

 scanner = new Scanner(System.in); 
     String topic = scanner.nextLine(); 
     topic = topic.toLowerCase(); 

     if (topic.contains("time") || topic.contains("date")){ 
     System.out.println("The time is " + Calendar.getInstance().getTime()); 
    } 
2
if (yourString.equals("hello") || yourString.equals("greetings")){ 
    //Execute code 
} 

如果你想你的字符串忽略大小写比较。使用equalsIgnoreCase()方法而不是equals()

3

由于在任何情况下语法都不正确,您的代码将无法编译。

答案是没有||操作符对boolean表情及String不是boolean值。

的有意义的方式来做到这一点是传统的方式:

if (a.equals("hello") || a.equals("greetings") { 
    .. 
} 

如果您有许多不同的令牌很多不同的选择,那么你应该考虑使用不同的方法,如Map<String, Consumer<String>>让你可以做一些事情像:

Map<String, Consumer<String>> mapping = new HashMap<>(); 
Consumer<String> greetings = s -> code; 

mapping.put("hello", greetings); 
mapping.put("greetings", greetings); 

... 

Consumer<String> mapped = mapping.get(a); 

if (mapped != null) 
    mapped.accept(a); 
0

以前的答案是正确的,对了点,但我想改变的一件事只是有点:

if ("hello".equals(a) || "greetings".equals(a)) { 
    //... 
} 

这样的话,你是不是冒着NullPointerException(因为你不能在null对象上执行方法,这将抛出如果anull)。如果您想忽略该情况,请使用equalsIgnoreCase(String)

,或者使用switch

switch(a) { 
    case "hello": //do something 
      break; 
    case "greetings": //do something 
      break; 
    default: //handle case where there is no match, if needed 
} 
+0

使用开关仍然会让我重复代码,我期待将它们结合在一起 – Albert

+0

是的,就你的情况而言。另外,根据上下文,你可能会发现''字符串字面值'.equals(string_var)'有用,尽管'Scanner'和/或'System.in'没有什么区别 – Luke

相关问题