2014-05-22 23 views
0

好的。我查看了如何製作迴文,看起來像使用reverse()方法似乎是我最好的選擇。但是,在我的代碼中,我遇到了一個我不明白的錯誤。在Java中使用reverse()命令?

import java.util.*; 
public class retreiveInput 
{ 
    private Scanner input = new Scanner(System.in); 
    private int fives = 0; 
    public retreiveInput(){ 

     fives = input.nextInt(); 

    } 
    public void check() 
    { 
     while(fives < 9999 || fives > 100000) 
     { 
      System.out.println("The number does not work! It is NOT 5 digits!"); 
      fives = input.nextInt(); 
     } 
     String five = Integer.toString(fives); 
     five.equalsIgnoreCase(new StringBuilder(five).reverse().toString()); 
      if(five = five.reverse()){ 

     } 
    } 
} 

在代碼的反向,它給我以下錯誤。 「方法reverse()未定義類型字符串」

任何想法如何解決這個問題?程序應該做的是,在if語句的reverse()點,程序應該檢查5的值是否等於5的倒數。

+2

該字符串類沒有reverse()方法,但StringBuilder確實 –

+0

那麼我將如何去使用StringBuilder來修復if語句? – user3348422

+0

@LuiggiMendoza我想錯誤是在'five.reverse()'。 '五'是類型字符串 –

回答

4
if(five = five.reverse()) 

在上面的代碼中,五是一個字符串。反向是StringBuilder()的一種方法。您的if語句中還存在一些錯誤。你想要這個

StringBuilder sbFive = new StringBuilder(five) 
if (five.equals(sbFive.reverse().toString())) 

還請注意,你可以做得更快一點。

更快地做到這一點的方法是在每一步開始並在比較過程中在中間相遇。它需要執行的一半:)

+0

沒關係。非常感謝!代碼終於起作用了!我在圖書館裏花了幾個小時試圖修復它。 – user3348422

+0

@ user3348422對不起,有一個包含括號的拼寫錯誤。 –

+0

@ user3348422如果可以,請接受此答案,並請不要將工作代碼編輯爲原始答案。這樣做會混淆未來的訪問者 –