【问题标题】:character array and for loop error字符数组和for循环错误
【发布时间】:2013-10-02 18:14:10
【问题描述】:

对于我正在学习的课程,我将创建一个程序来测试字符串是否为回文。我们应该每次只使用一个 8 个字符的字符串并以这种方式对其进行硬编码,但我想超越并制作一些东西来测试任何字符串。不幸的是,这段代码似乎返回 true,老实说,我不确定为什么。

    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
}

【问题讨论】:

    标签: java arrays string for-loop methods


    【解决方案1】:

    因为

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

    for 循环中的代码永远不会被执行,因为 i 永远不会大于 0

    编辑: 而且

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

    有点错误,因为假设你的字符串是女士,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;
      }
    
    }
    

    【讨论】:

    • 是的,for循环迭代次数的上限需要更改。
    • OHHH 谢谢,我不知道我为什么这么说,我的意思是 i
    【解决方案2】:

    使用for循环和char数组的回文测试方法如下:

      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;
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-25
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多