为什么我的代码检查数字是否为回文并不起作用?

时间:2014-09-10 23:45:31

标签: java algorithm numbers palindrome

我的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");
            }
        }
    }
}

如果输入的数字是零,代码将只识别回文。我无法理解原因。

5 个答案:

答案 0 :(得分:1)

这是因为x的值最终会改变。这不是程序末尾的原始数字。 所以在x下方采取另一个变量,如: int y = x; 最后,在使用“if”条件时,使用y的这个值进行比较而不是使用x。它将完美运行。

int x = scan.nextInt();

int y = x;

if(y == isPalindrome)像这样添加新变量。

答案 1 :(得分:0)

解决方案的问题在于您在while循环中修改x。您对(x == isPalindrome)的最终检查将始终失败,因为只有当x等于零时才会到达该语句。

您需要将原始x值保存在另一个变量中,并使用它来检查isPalindrome。

答案 2 :(得分:0)

问题在于,在处理过程中,x的值正在从最初输入的值改变 - 它总是最终为0。

所以,你必须保留输入值,如下所示:

Scanner scan = new Scanner(System.in);
int original = scan.nextInt();
int x = original;

然后使用原始值进行最终比较,如下所示:

if (original == isPalindrome){

答案 3 :(得分:0)

以下是我的方法:我会更多地使用这些库并编写更少的代码。

我建议您学习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);
    }
}

答案 4 :(得分:0)

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