2017-01-22 46 views
0

我是全新的,完全丟失。我正在尋找一個教程或資源,可以向我解釋如何執行此操作:條件邏輯和字符串操作在JAVA

爲每個展開的縮寫輸出一條消息,然後輸出展開的行。

例如,

Enter text: IDK how that happened. TTYL. 
You entered: IDK how that happened. TTYL. 

Replaced "IDK" with "I don't know". 
Replaced "TTYL" with "talk to you later". 

Expanded: I don't know how that happened. talk to you later. 

我知道該怎麼做了userText.replace部分改變IDKI don't know,但我不知道如何將它設置爲搜索的字符串爲IDK

+0

爲什麼你需要搜索自己? '替換'已經搜索並替換你.... – Li357

+0

我會建議看看HashMap 爲:https://docs.oracle.com/javase/8/docs/api/java/util/ HashMap.html –

+0

不確定,正如我所說,不知道我在做什麼,但我知道我應該使用條件格式和idk如何做到這一點 –

回答

0

您可以使用String.indexOf()找到給定的字符串的第一個實例:

String enteredText = "IDK how that happened. TTYL."; 
int pos = enteredText.indexOf("IDK"); // pos now contains 0 
pos = enteredText.indexOf("TTYL"); // pos now contains 23 

如果indexOf()無法找到字符串,則返回-1。

一旦你知道一個價值發現(通過測試該pos != -1),執行您的更換和輸出消息。

0

使用String.indexOf()檢查,看看是否在輸入字符串存在的每個縮寫,replaceAll()修改字符串如果是這樣:

import java.util.Scanner; 

class Main { 
    public static void main(String[] args) { 
    Scanner scanner = new Scanner(System.in); 
    System.out.print("Enter text: "); 
    String text = scanner.nextLine(); 
    System.out.println("You entered: " + text); 
    if(text.indexOf("IDK") != -1) { 
     System.out.println("Replaced \"IDK\" with \"I don't know\""); 
     text = text.replaceAll("IDK", "I don't know"); 
    } 
    if(text.indexOf("TTYL") != -1) { 
     System.out.println("Replaced \"TTYL\" with \"talk to you later\""); 
     text = text.replaceAll("TTYL", "talk to you later"); 
    } 
    System.out.println("Expanded: " + text); 
    } 
} 

輸出:

Enter text: IDK how that happened. TTYL. 
You entered: IDK how that happened. TTYL. 
Replaced "IDK" with "I don't know" 
Replaced "TTYL" with "talk to you later" 
Expanded: I don't know how that happened. talk to you later. 

試試吧here!

注:這上面實現不處理輸入的任何不規則的市值爲這個問題我建議你看看toLowerCase()toUppperCase()