2013-05-15 35 views
2

我的代碼是:比較字符串時可以創建OR語句嗎?

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

我想知道如果我能代替,如果用線沿線的一些事情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是我的第二類對象它的方式,它完美地輸出時間。

回答

1

您正確使用||邏輯或運算符,但您使用它的方式有誤。從第一個示例中獲取ifelse if中的每個特定條件,並將||置於它們之間,只需一個if,而不需要else if

3

你需要句話這樣說:你可以使用正則表達式一個比較

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

非常感謝你! –

+0

這絕對有效,但你不需要像這樣描述它。 –

+0

很明顯,還有其他方法可以做到這一點,但這最接近OP想要表達的內容。 – Blorgbeard

4

,但它只能移動或從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

最明顯的方法是這樣:

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; 
} 
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(); 
     }  
    } 
} 
-1

假設在條件狀態中只有兩個可能的選項nt,你可以用這個

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

p.s.我不會做「案件」。在這種情況下,這並不重要,因爲它只有兩種選擇,但在使用案例時,每個案例行將根據條件「TRUE」單獨進行檢查,並且這可能需要很長時間才能處理長時間的程序。

+0

我因爲誤解了這個問題而低估了你 - 條件陳述在這種情況下並沒有幫助。和IIRC我在Java 101中獲得了A + :) – Blorgbeard

+0

我是LOTUS Marketing Solutions的高級Java程序員。我告訴你它確實有效。但我沒有時間。所以繼續認爲你是對的,誤導別人。這個網站不關於誰知道和誰幫助。這個網站充滿了不成熟和有針對性的downvoting。 :等待被暫停: – LOTUSMS

+0

有條件的陳述有效,但在這種情況下它們不起作用。你如何閱讀理解?另外,「case」語句是[快速](http://stackoverflow.com/a/767849/369)。並且不要抱怨,你不會被「暫停」。你聽起來不像我的高級開發人員。 – Blorgbeard

相關問題