【问题标题】:Java while loop query [closed]Java while循环查询[关闭]
【发布时间】:2018-08-14 12:40:24
【问题描述】:

这个while 代码工作正常,它是一个检查回文的程序。

public class Solution {
    public static boolean checkPalindrome(String str){
        int i=0;
        int j= str.length()-1;
        while(i<j)
        {
            if(str.charAt(i)!=str.charAt(j))
            {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}

但是在这个版本中会发生什么,你期望输出是什么?

public class Solution {
    public static boolean checkPalindrome(String str){
        int i=0;
        int j= str.length()-1;
        while(i<j)
        {
          if(str.charAt(i)!=str.charAt(j))
          {
              return false;
          }
          else
          {
              return true;
          }
          i++;
          j--;
        }
    }
}

【问题讨论】:

  • 为什么不能自己运行看看?
  • 这是给我们的任务吗?或者你想问点别的?
  • 第二个代码是错误的,因为它只会检查字符串中的第一个和最后一个字符。 return 退出循环。
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 On topichow to ask 在这里申请。 StackOverflow 不是设计、编码、研究或教程服务。

标签: java algorithm loops methods conditional-statements


【解决方案1】:

在您的第二个代码块中,您首先检查第一个字符是否与最后一个字符相同。

如果不是,则返回 false。

否则,返回真。

所以这不会是一个有效的回文检查。它只检查第一个和最后一个字母是否相同,并忽略中间的字母。

【讨论】:

    猜你喜欢
    • 2017-04-27
    • 1970-01-01
    • 2015-04-24
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2019-07-14
    • 1970-01-01
    相关资源
    最近更新 更多