Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to compare two ints

This is my first time asking a question and I have tried to search the existing threads first. My program is meant to ask the user to enter a 5-digit number and it will check to see if it is a palindrome by reversing the number and then comparing the original number to the reverse. I also put in some verification steps there to reject the number if it is longer or shorter than 5 digits. Everything seems to work until it gets to the part comparing the original number and the reversed number. Here is my code:

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.");
        }
    }
}
like image 704
jinx520 Avatar asked Jan 02 '23 07:01

jinx520


2 Answers

Look at what you are doing here!

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

Which means that after the loop, n will no longer be the same n that the user entered.

To fix this, copy n to another variable and modify that instead.

int temp = n;
while (length == 5 && temp != 0) {
    reverse = reverse * 10;
    reverse = reverse + temp % 10;
    temp = temp / 10;
}
like image 68
Sweeper Avatar answered Jan 12 '23 00:01

Sweeper


it's more easy to convert the number to an array and reverse it instead of calculating it:

let reverseNumber = parseInt(12345.toString().split("").reverse().join());
like image 38
nologin Avatar answered Jan 12 '23 00:01

nologin