为什么我的代码检查数字是否为palindrom不起作用?
我的Java代码在这里:
import java.util.Scanner; public class task2 { public static void main(String args[]) { System.out.print("Input a 3 digit int"); Scanner scan = new Scanner(System.in); int x = scan.nextInt(); int isPalindrome = 0; while (x != 0) { isPalindrome = isPalindrome*10 + x % 10; x /= 10; } { if (x == isPalindrome){ System.out.print ("Yes, this is a palindrome!"); } else { System.out.print("No, try again"); } } } }
如果输入的数字是零,则代码将仅识别回文。 我无法理解为什么。
这是因为x的值最终会改变。这不是程序末尾的原始数字。 所以在x之下取另一个变量,如:int y = x; 最后,在使用“if”条件时,使用y的这个值进行比较而不是使用x。 它将完美运行。
int x = scan.nextInt();
int y = x;
if(y == isPalindrome)像这样添加新变量。
解决方案的问题是您在while循环中修改x。 您对(x == isPalindrome)的最终检查将始终失败,因为只有当x等于零时才会到达该语句。
您需要将原始x值保存在另一个变量中,并使用它来检查isPalindrome。
问题在于,在处理过程中,x的值正在从最初输入的值改变 – 它总是最终为0。
因此,您必须保留输入值,如下所示:
Scanner scan = new Scanner(System.in); int original = scan.nextInt(); int x = original;
然后使用原始值进行最终比较,如下所示:
if (original == isPalindrome){
这是我如何做到的:我更多地使用这些库并编写更少的代码。
我建议您学习Sun Java编码标准并开发格式化风格。 可读性促进理解。 风格和整洁很重要。
package misc; public class PalindromeChecker { public static void main(String args[]) { for (String arg : args) { System.out.println(String.format("arg '%s' is" + (isPalindrome(Integer.valueOf(arg)) ? "" : " not") + " a palindrome", arg)); } } public static boolean isPalindrome(int value) { String s = Integer.toString(value); String reversed = new StringBuilder(s).reverse().toString(); return reversed.equals(s); } }
在x
上执行以下操作时:
x /= 10;
你正在修改它的值 – 所以它不再包含来自的输入:
int x = scan.nextInt();
正如Narendra Jadon建议的那样 – 您可以将原始值保存到另一个变量中,并在尝试比较时使用它:
if (x == isPalindrome){
使用int转换为String的替代解决方案:
public boolean isPalindrom(int n) { return new StringBuilder("" + n).reverse().toString().equals("" + n); }