编写递归回文数判断方法时出现Not A Statement编译错误,求排查
问题根源与修复方案
嘿,这个编译错误的原因其实很直白:short是Java的保留关键字,它专门用来声明短整型(16位整数)变量,不能被当作自定义变量名使用,这就是编译器提示“不是一条语句”的核心原因。
快速修复
只需要把变量名换成任意非关键字的名称就行,比如shortenedNumber:
public boolean isPalindrome(int x) { String str = Integer.toString(x); if(str.length() <= 1){ return true; } else{ char first = str.charAt(0); char last = str.charAt(str.length()-1); if (first == last){ int shortenedNumber = Integer.parseInt(str.substring(1, str.length()-1)); return isPalindrome(shortenedNumber); } else{ return false; } } }
额外优化提示
这里还有个潜在的小问题:如果原数字是类似1001这样的数,截取中间部分后会得到空字符串,此时Integer.parseInt会抛出NumberFormatException。其实我们可以直接递归处理字符串,不用来回转换整数,这样既安全又高效:
public boolean isPalindrome(int x) { // 先处理负数情况,负数不可能是回文数 if (x < 0) return false; return checkPalindrome(Integer.toString(x)); } private boolean checkPalindrome(String str) { if (str.length() <= 1) { return true; } if (str.charAt(0) != str.charAt(str.length() - 1)) { return false; } return checkPalindrome(str.substring(1, str.length() - 1)); }
另外还加了负数的判断,毕竟负数带负号,肯定不是回文数,提前过滤能减少不必要的递归。
内容的提问来源于stack exchange,提问作者timeRocket
相关产品推荐
相关产品推荐

