试图比较两个整数

时间:2019-02-10 08:15:08

标签: java int comparison-operators

这是我第一次问一个问题,我尝试首先搜索现有线程。我的程序旨在要求用户输入一个5位数的数字,它将通过反转数字然后将原始数字与反向数字进行比较,以检查它是否是回文。如果数字长于或短于5位,我还会在其中进行一些验证,以拒绝该数字。直到所有部分都比较原始数字和反向数字为止,一切似乎都可以正常工作。这是我的代码:

import java.util.Scanner;

public class Palindromes {
    public static void main(String args[]) {
        int n, reverse = 0;
        System.out.println("Enter a 5-digit integer to see if it is a palindrome.");
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        int length = String.valueOf(n).length();
        while (length > 5 || length < 5) {
            System.out.println("Error: integer must be 5 digits in length.");
            System.out.println("Enter a 5-digit integer.");
            n = in.nextInt();
            length = String.valueOf(n).length();
        }
        while (length == 5 && n != 0) {
            reverse = reverse * 10;
            reverse = reverse + n % 10;
            n = n / 10;
        }
        System.out.println("Reversed number is: " + reverse);
        if (n == reverse) {
            System.out.println("Congratulations! Your number is a palindrome!");
        } else {
            System.out.println("Sorry.  Your number isn't a palindrome.");
        }
    }
}

2 个答案:

答案 0 :(得分:6)

看看你在这里做什么!

while (length == 5 && n != 0) {
    reverse = reverse * 10;
    reverse = reverse + n % 10;
    n = n / 10; // <----- You are changing "n"!
}

这意味着在循环之后,n将不再与用户输入的n相同。

要解决此问题,请将n复制到另一个变量,然后对其进行修改。

int temp = n;
while (length == 5 && temp != 0) {
    reverse = reverse * 10;
    reverse = reverse + temp % 10;
    temp = temp / 10;
}

答案 1 :(得分:3)

将数字转换为数组并将其取反而不是计算它更容易:

let reverseNumber = parseInt(12345.toString().split("").reverse().join());