2013-03-09 58 views
0

爲什麼我的代碼將舊單詞與新單詞相結合?輸入是「香蕉」輸出「香蕉」新輸入「狗」輸出「香蕉」?組合在一起的單詞

public static void main(String [] args) 
{ 
    Scanner keyboard = new Scanner(System.in); 
    String word, afc, newWord; 
    String s=""; 

    do 
    { 
     word=keyboard.next().toLowerCase(); 
     int i =word.length()-1; 
     char firstLetter=word.charAt(0); 
     afc=word.substring(1); 
     newWord= afc+firstLetter; 

     for(; i>=0 ;) 
     { 
      s += newWord.charAt(i--); 
     } 
     System.out.println(word + "," + s); 

     if (s.equals(word)) 
      System.out.println("Words are equal."); 
     else 
      System.out.println("Words are not equal."); 
    } 
    while (!(word.equals("quit"))); 

} 
+0

它是什麼,你希望你的代碼,這樣做? – uba 2013-03-09 11:47:56

+0

分隔新的輸入。每當你輸入一個新單詞時,它都會將新單詞與舊單詞相結合。 – Aaronooooooo 2013-03-09 11:51:37

+0

我在問你的代碼的目的。你能詳細說明你的代碼應該做什麼嗎? – uba 2013-03-09 11:54:22

回答

1

你是不是在循環的開始清除s變量。

應該

Scanner keyboard = new Scanner(System.in); 
    String word, afc, newWord;  

    do 
    { 
     String s=""; 
     ... 
0

試試這個

public static void main(String [] args) 
{ 
    Scanner keyboard = new Scanner(System.in); 
    String word, afc, newWord; 
    String s=""; 

    do 
    { 
     s = ""; 
     word=keyboard.next().toLowerCase(); 
     int i =word.length()-1; 
     char firstLetter=word.charAt(0); 
     afc=word.substring(1); 
     newWord= afc+firstLetter; 

     for(; i>=0 ;) 
     { 
      s += newWord.charAt(i--); 
     } 
     System.out.println(word + "," + s); 

     if (s.equals(word)) 
      System.out.println("Words are equal."); 
     else 
      System.out.println("Words are not equal."); 
    } 
    while (!(word.equals("quit"))); 

} 
+0

不起作用。該代碼只是將「狗」一詞改爲「ogd」。它假設爲「狗」,「dgo」。 – Aaronooooooo 2013-03-09 12:09:20

+0

@Aaronooooooo現在檢查。編輯。 – uba 2013-03-09 12:12:00