2017-01-22 18 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()