2017-10-17 35 views
-2

我是java的初學者,並且在用charAt()打印userinput時遇到了麻煩。我需要創建一個採用userinput的程序,並在該文本中的元音之前添加「op」。 (例如:用戶輸入 - >「美麗」將被翻譯爲「Bopeautopifopul」)我正在努力想像如何寫這個。到目前爲止,我已經想出了這一點。用charAt()打印userinput?

import java.util.Scanner; 
public class oplang { 
static Scanner userinput = new Scanner(System.in); 
public static void main(String[] args) { 

    char c ='a'; 
    int n,l; 

    System.out.println("This is an Openglopish translator! Enter a word here to translate ->"); 
    String message = userinput.nextLine(); 
    System.out.println("Translation is:"); 
    l = message.length(); 

    for (n=0; n<l; n++); 
    { 
     c = message.charAt(); 
     if (c != ' '); 
    { 
     System.out.println(" "); 
    } 
    c++; 
} 
}} 
+2

'C = message.charAt(N);' –

+1

https://ideone.com/FoVdYs – shmosel

+2

如果共de需要添加''op「',我怎麼在代碼中找不到一個'op'? ---爲了使'for'和'if'語句正常工作,請刪除這兩行末尾的';'。 – Andreas

回答

1

我會用一個正則表達式,組中的任何元音 - 與op隨後分組替換它(使用(?i)第一,如果它應該是不區分大小寫)。像,

System.out.println("Translation is:"); 
System.out.println(message.replaceAll("(?i)([aeiou])", "op$1")); 

如果你不能使用正則表達式,那麼我會喜歡一個for-each循環,像

System.out.println("Translation is:"); 
for (char ch : message.toCharArray()) { 
    if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) { 
     System.out.print("op"); 
    } 
    System.out.print(ch); 
} 
System.out.println(); 

的東西,如果你絕對必須使用charAt,可以是這樣寫

System.out.println("Translation is:"); 
for (int i = 0; i < message.length(); i++) { 
    char ch = message.charAt(i); 
    if ("aeiou".indexOf(Character.toLowerCase(ch)) > -1) { 
     System.out.print("op"); 
    } 
    System.out.print(ch); 
} 
System.out.println(); 
+0

不錯,但我覺得這項任務需要OP使用charAt –

+0

@BrunoDelor *氣味*就像一個措辭不佳的任務給我。 –

+0

非常感謝你@ElliottFrisch! – CMCK