Search code examples
javapalindrome

I defined a random number and i want to check if it is a palindrome java


import java.util.Random;

public class Loop6 {
    public static void main(String[] args) {

        Random number = new Random();
        int value = number.nextInt(1000);
        System.out.println("random number : " + " " + value);

        int rev = 0;
        int dig;

        while (value > 0) {
            dig = value % 10;
            rev = rev * 10;
            rev = rev + dig;
            value = value / 10;
        }
        System.out.println("rev is : " + "" + rev);
        if(value==rev) {
            System.out.println("Palindrome");

        }

    }
}

Solution

  • You code is almost fine, it's just you're updating the initial random number which is not what you want. To keep changes to the code at minimal, I propose you to add a new variable and compare it to the result of your reverse algorithm.

    import java.util.Random;
    
    public class Loop6 {
        public static void main(String[] args) {
    
            Random number = new Random();
            int randomNumber = number.nextInt(1000);  // introduce the initial variable
            int value = randomNumber;  // introduce the variable that will be updated
            System.out.println("random number : " + " " + value);
    
            int rev = 0;
            int dig;
    
            while (value > 0) {
                dig = value % 10;
                rev = rev * 10;
                rev = rev + dig;
                value = value / 10;
            }
            System.out.println("rev is : " + "" + rev);
            if (randomNumber == rev) {  // compare the initial variable and the reverse result
                System.out.println("Palindrome");
    
            }
    
        }
    }