2013-09-26 43 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; 
      }