【问题标题】:Check if a string is a Palindrome (using methods)检查字符串是否为回文(使用方法)
【发布时间】:2016-01-31 10:26:18
【问题描述】:

我不知道为什么以下方法不起作用。它显示:

Palindrome.java:97:错误:<identifier> 预期

该方法接受一个字符串参数,如果提供的字符串是回文,则应返回truefalse

public static boolean checkPalindrome(checkString) {
    boolean test = true;
    int left = 0;
    int right = checkString.length() - 1;
    while (left < right && test) {
        if (checkString.charAt(left) != checkString.charAt(right)) {
            test = false;
        }
        right--;
        left++;
    }
    return test;
}

【问题讨论】:

  • “不工作”是什么意思?它做了什么不该做的事?有什么错误吗?
  • 当您发布问题时,您的方法中没有数据类型。是不是打错字了?
  • @Tunaki 除了缩进之外,您不应该更改源代码。您刚刚删除了问题的原因。
  • @RealSkeptic 上帝,你是对的......我在我的 IDE 中正确格式化了它,它自动更正了错误......甚至没有注意到它,认为这是一个错字
  • 其实你们不是错字:(

标签: java eclipse string methods boolean


【解决方案1】:

第一行有错,应该是:

public static boolean checkPalindrome(String checkString)   

你必须在参数之前提供数据类型^

【讨论】:

    【解决方案2】:

    我认为你在第一行写错了,应该是:

    public static boolean checkPalindrome(String checkString)   
    

    你必须在参数之前提供数据类型^

    【讨论】:

      【解决方案3】:

      问题是这条线

      public static boolean checkPalindrome(checkString)
      

      应该是

      public static boolean checkPalindrome(String checkString)
      

      只是一个建议,但您也可以减少正在使用的变量

      int len = checkString.length();
      for (int i = 0; i < len / 2; i++) {
          if (checkString.charAt(i) != checkString.charAt(len - i -1)) {
              return false;
          }
      }
      return true;
      

      【讨论】:

      • 高效?不,因为这个 for 循环以及你的 while 循环迭代直到length/2。可读吗?是的
      猜你喜欢
      • 2012-04-05
      • 2012-01-16
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多