2013-03-09 60 views
2

我將新詞與原詞進行比較時出現問題。我想輸入像「香蕉」這樣的詞,並把第一個字母結尾,它應該拼寫爲「香蕉」。這兩個詞是平等的。如果我輸入「狗」,它會變成「dgo」。但在我的代碼中,如果我輸入「香蕉」,它仍然表明它不平等。 Idk該做什麼。向後拼寫詞

import java.util.Scanner; 
public class Project9 
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"))); 

} 
} 
+2

只是一個提示:密切注意語言約定。 Java使用縮進來使代碼更具可讀性。請參閱官方風格指南:http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#262 但首先,編程應該很有趣。所以,如果你有時間,請將它加入書籤並回復它。 – 2013-03-09 09:43:46

+1

你的代碼是......獨一無二的。試着想:「我如何編寫自己的代碼才能在5年內即時瞭解它。」 – sschrass 2013-03-09 09:55:27

回答

1

的問題是,你的代碼打印反字與

for(; i>=0;) 
    System.out.print(newWord.charAt(i--)); 

但此時你用

newWord.equals(word) 

比較非反轉的版本我想你想要的東西如:

String s = ""; 
for(; i>=0;) 
    s += newWord.charAt(i--); 
System.out.println(s); 

if (s.equals(word)) 
    ... 
+0

謝謝幫助了很多! – Aaronooooooo 2013-03-09 10:25:01

0

您正在比較香蕉ananab
除此之外,您正在做一個小任務的許多操作。
字符串操作不是一個好的做法,因爲每次更改字符串時,都會創建一個新的String對象。我已經寫了你的需求的代碼,希望它有助於
字符數組比字符串更好,當你需要處理很多次

public static void main(String [] args) 
{ 
    Scanner keyboard = new Scanner(System.in); 
    String word, newWord; 
    do 
    { 
     word=keyboard.next().toLowerCase(); 
     int i =word.length()-1; 
     char[] ca=new char[i+1]; 
     ca[0]=word.charAt(0); 
     for(int j=1; i>0;j++) 
     { 
      ca[j]=word.charAt(i--); 
     } 
     newWord= new String(ca); 

     System.out.println(word+","+newWord); 

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

我還是新來的java。我還沒有學習陣列。 – Aaronooooooo 2013-03-09 10:41:02