2015-11-04 152 views
0

我需要輸入包含單個*字符的字符串,然後輸入第二個字符串。 *將被替換爲第二個字符串。例如,如果用戶輸入字符串「d * g」和「in」,則程序輸出ding。 原始字符串只能包含字母,大寫或小寫字母,空格和製表符以及一個*。替換字符串可以是Java中的任何合法字符串。 如果第一個字符串不包含*「Error:no *」應該輸出。 如果第一個字符串包含字母,空格或製表符以外的任何內容,則應打印「錯誤:不正確的字符」。如果第一個字符串沒有*,我不必檢查不正確的字符,則只應輸出「Error:no *」。如何用字符串替換字符?

我有什麼至今:

import java.io.*; 
import static java.lang.System.*; 

import java.util.Scanner; 
import java.lang.Math; 


class Main{ 

    public static void main (String str[]) throws IOException { 
Scanner scan = new Scanner(System.in); 

char letter; 
int i; 

    System.out.println("Enter the first String:"); 
String wc = scan.nextLine(); 
    System.out.println("Enter the replacement String:"); 
String replace = scan.nextLine(); 
String my_new_str = wc.replaceAll("*", replace); 
for (i = 0; i < wc.length(); i++) 
     { 
      letter = wc.charAt(i); 

      if (! (letter == '*')){ 
      System.out.println("Error: no *");} 
      System.out.println(""+ my_new_str); 







} 

} 
} 
+0

因爲''是一個特殊的元字符,你需要像'String my_new_str = wc.replaceAll(「\\ *」,replace)那樣轉義*。 ' –

回答

0

我相信你想String.replace(CharSequence, CharSequence)(不replaceAll,需要一個正則表達式)。

String my_new_str = wc.replaceAll("*", replace); 

應該

String my_new_str = wc.replace("*", replace); 

您可以測試它像

String wc = "d*g"; 
String replace = "in"; 
System.out.println(wc.replace("*", replace)); 

和get(的要求)

ding 
+0

修復了連接問題但程序正在返回:錯誤:否* ding ding 錯誤:否* ding –