2013-09-26 45 views
0

對於我正在使用的類,我將創建一個程序來測試字符串是否是迴文。我們應該每次只使用8個字符的字符串,並以這種方式對其進行硬編碼,但是我想要超越並做出測試任何字符串的東西。不幸的是,這段代碼似乎總是返回真實的,我真的不知道爲什麼。字符數組和循環錯誤

public static boolean palindromeTest(String input){ 
    //This portion declares variables necessary for testing, and modifies them if necessary. 
    int inputLength=input.length(); 
    char[] Chars=input.toCharArray(); 
    for(int j=0; j<inputLength; j++){ 
     Character.toLowerCase(Chars[j]); //makes all characters in input lower case 
     //This portion performs the palindrome test 
    } 
    if(inputLength%2>0){ //if length is odd 
     inputLength=(inputLength-1)/2; 
     for(int i=0; i>0; i++){ 
      if(Chars[i]!=Chars[inputLength-i]) //tests equality first and last in pairs via for loop 
       return false; //break; 
     } 
    }else{ //if length is even 
     inputLength=(inputLength)/2; 
     for(int i=0; i>0; i++){ 
      if(Chars[i]!=Chars[inputLength-i]) //tests equality first and last in pairs via for loop 
       return false; //break; 
     } 
    } 
    return true; //if all tests are passed, input is indeed a palindrome 
} 

回答

3

正是因爲

for(int i=0; i>0; i++){ 

內的代碼循環將永遠不會被執行作爲i是從不大於0

編輯: 此外

if(charArray[i]!=charArray[inputLength - i]) 

有點不對,cuz可以說你ř字符串是女士,inputLength = inputLength-1使得上述條件,以檢查「m」和「d」,這不應該如何工作

正確的解決方案將使用用於循環和焦炭是

inputLength = inputLength/2; 
int j= input.length()-1; 

for(int i =0; i< inputLength; i++, j--) { 

    if(charArray[i]!=charArray[j]) { 
    return false; 
    } 

} 
+0

yup,循環迭代次數的上限需要改變。 –

+0

OHHH謝謝,我不知道爲什麼我這麼說,我的意思是我

+0

@PeaceBlaster:請編輯您的問題。 –

0

迴文測試方法陣列如下:

public static boolean palindromeTest(String input){ 
      char[] Chars=input.toCharArray(); 
      for(int i=0,j=Chars.length-1;i<j;i++,j--){ 
       if(Chars[i]!=Chars[j]){ 
        return false; 
       } 
      } 
      return true; 
      }