简体   繁体   中英

wrong output of program(logical error)

I am coding on textpad(java) in windows 8. I have written a program to check whether the given number is a palindrome or not. But for every entered choice(irrespective of what the number is), it always displays that it is not a palindrome. Please help me by telling me what is wrong with my code.

class reversenumber
{
    private int n=99;
    private int rem=0;
    private int rev=0,d;

    public void calc()
    {
        while(n>=0)
        {
            rem=n%10;
            rev=(rev*10)+rem;
            n=n/10;

            if(n==0)
            {
                break;
            }
        }
        if(rev==n)
        {
            System.out.println("The number is a palindrome");
        }
        else
        {
            System.out.println("The number is not a palindrome");
        }
    }

    public static void main(String args[])
    {
        reversenumber x=new reversenumber();
        x.calc();
    }
}

Here is the issue:

if(rev==n)
    { 
        System.out.println("The number is a palindrome");
    } 

Since n has already become 0, you are comparing it will reverse of initial value of n, since it is never equal therefore you are getting wrong output. So you can make another variable and assign n's value to it initially. Then inside if you can compare rev with other number. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM