2012-12-13 16 views
0

我寫一個程序,如果在以下兩行有人類型:我在程序中做了什麼錯誤?

你好,我想訂一個FZGH

的兒童套餐

程序將輸出這樣的:

你好,我想訂一個孩子的吃飯

換句話說,在「FZGH」用戶輸入入刑將與第二行的字來代替,就可以看出:「FZGH」被「KID'S MEAL」取代。有點明白我的意思嗎?如果沒有,我可以詳細說明,但這是我能解釋的最好的。

我真的接近解決這個問題!我當前的輸出是:HELLO,我想要命令一個FZGH KID的用餐

我的程序並沒有用「KID'S MEAL」取代「FZGH」,我不知道這是爲什麼。我認爲通過使用.replaceAll(),它會用「KID'S MEAL」代替「FZGH」,但那並沒有真正發生。這是我的計劃至今:

public static void main(String[] args) { 
    sentences(); 
} 

public static void sentences() { 
    Scanner console = new Scanner(System.in); 
    String sentence1 = console.nextLine(); 
    String sentence2 = console.nextLine(); 
    //System.out.println(sentence1 + "\n" + sentence2); 
    String word = sentence1.replaceAll("[FZGH]", ""); 
    word = sentence2; 
    System.out.print(sentence1 + word); 

} 

哪兒了我陷入困境,導致FZGH產出仍然出現?

回答

1

使用

sentence1 = sentence1.replaceAll("FZGH", ""); 
String word = sentence2; 

你的第一個(主)問題是,你正在創建一個新的名爲Stringword,那你設置的sentence1.replaceAll("[FZGH]", "")值。之後您立即將word的值更改爲sentence2,以便更換失敗。

相反,設置sentence1sentence1.replaceAll("FZGH", "");將改變sentence1不再包含字符串"FZGH",這是你要的東西。你根本不需要word的值,所以如果你想刪除它,它不會受到傷害。

此外,使用[FZGH]將取代所有F的,Z的,G的,和H的距離與字符串,你應該使用FZGH代替,因爲這隻會刪除在所有四個字母的情況下,行。

+0

啊,這就是我出錯的地方!感謝您澄清 – user1029481

+0

請確保現在您的問題已經解決,接受答案。乾杯! –

+0

Okeydokey,會做 – user1029481

0

您重新分配字符串 「字」

到位線:

String word = sentence1.replaceAll("[FZGH]", ""); 
word = sentence2; 
System.out.print(sentence1 + word); 

使用下面的行

sentence1 = sentence1.replaceAll("[FZGH]", ""); 
System.out.print(sentence1 + sentence2); 
+0

okeydokey,謝謝 – user1029481

1

我覺得你有幾個失誤。也許下面是關閉...

public static void main(String[] args) { 
    sentences(); 
} 

public static void sentences() { 
    Scanner console = new Scanner(System.in); 
    String sentence1 = console.nextLine(); 
    String sentence2 = console.nextLine(); 
    String sentence3 = sentence1+sentence2; 
    String final = sentence3.replaceAll("FZGH", ""); 
    System.out.print(final); 
} 
+0

好吧,我會記住這一點,謝謝 – user1029481

0

其實replace方法返回一個字符串,應該再次分配給sentence1。你可以運行這個代碼它的工作正常。 public static void main(String [] args){ sentences(); }

public static void sentences() { 
     Scanner console = new Scanner(System.in); 
     String sentence1 = "HELLO, I’D LIKE TO ORDER A FZGH"; 
     String sentence2 = "KID’S MEAL"; 
     //System.out.println(sentence1 + "\n" + sentence2); 
     sentence1 = sentence1.replace("FZGH", ""); 
     String word = sentence2; 
     System.out.print(sentence1 + word); 

    }