2014-11-13 64 views
-1

所以我正在檢查一個詞輸入以查看它是否是迴文。我的代碼中的錯誤似乎是與兩個字符串的比較。我使用.equals()來測試相等的值,但它不起作用。 有什麼建議嗎?如何向後打印文字

這裏是我的代碼:

public class PalindromeTask08 
{ 

public static void main(String[] args) 
{ 
    Scanner in = new Scanner (System.in); 
    int count = 5; 
    int x =0; 

    //loops to input a word 
    do{ 
     System.out.println("input a word"); 
     String answer = in.next(); 
     char[] wordBackwards=new char[answer.length()]; 


     System.out.printf("The lenght of the word inputted is: %s%n", answer.length()); 

     for(int i= answer.length() ; i>0 ; --i) 
     { 

      wordBackwards[x] = answer.charAt(i-1); 
      x++; 
     } 

     x=0; 

     wordBackwards.toString(); 
     System.out.println(wordBackwards); 

     if (answer.equals(wordBackwards)) 
     { 
      System.out.printf("%s is a palindrome", answer); 
      --count; 
      System.out.printf("you have %d more attempts", count); 
     } 
     else 
     { 
      System.out.printf("%s is NOT a palindrome", answer); 
      --count; 
      System.out.printf("you have %d more attempts", count); 

     } 

    }while(count!=0); 
    in.close(); 



    } 

} 
+2

這和從構造函數中打印日期有什麼關係?你有沒有至少讀過你的程序的輸出?你不覺得'wordBackwards'的價值不像你期望的那樣嗎? –

回答

1

你的問題是

wordBackwards.toString(); 

它沒有做其他任何事情,你返回數組的地址。
您需要更換這樣的,使其工作:

... 
x=0; 
String backWordsString = new String(wordBackwards); 
System.out.println(backWordsString); 
if (answer.equals(backWordsString)) { 
... 

更簡單的方式來做到這將是

public class PalindromeTask08 { 
    public static void main(String[] args) { 
     Scanner in = new Scanner (System.in); 
     int count = 5; 
     int x =0; 

     //loops to input a word 
     do { 
      System.out.println("input a word"); 
      String answer = in.next(); 
      if (answer.equals(new StringBuilder(answer).reverse().toString())) { 
       System.out.printf("%s is a palindrome", answer); 
      } else { 
       System.out.printf("%s is NOT a palindrome", answer); 
      } 
      --count; 
      System.out.println("\n you have %d more attempts "+ count); 
     } while(count!=0); 
     in.close(); 
    } 
} 

要了解更多關於StringBuilder

+0

爲什麼StringBuffer而不是StringBuilder? –

+1

你是對的StringBuilder更好! – StackFlowed

+0

感謝您的快速響應 – Crazypigs