Jump to content

error in palindrome

- - - - -

  • Please log in to reply
4 replies to this topic

#1
arunjib

arunjib

    Learning Programmer

  • Members
  • PipPipPip
  • 76 posts
Please help me in following code. The program always returns else part

public class reverseNumber

{

public void func(int n)

{

int d,r; r=0;

do

{

d=n%10;   // returns remainder

r=r*10+d;

n=n/10;   // returns quotient

}while(n!=0);

if(n==r)

System.out.println("palindrome");

else

System.out.println("not palindrome");

}

}


#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
}while(n!=0);

if(n==r)
n must always equal 0 at the end of that do loop. Your do while loop adds value to r, so inevitably if n started > 9 then r must be > 0, therefore n will never == r. Thus, you get "not palindrome". Why are you using this method to determine a palindrome anyway, why not just take user input String object, make a reversed string, then use .equals()?
Wow I changed my sig!

#3
arunjib

arunjib

    Learning Programmer

  • Members
  • PipPipPip
  • 76 posts
Thank you ZekeDragon. I have already solved the problem with the help of the program given in the following link .

Java Palindrome Number,Java Palindrome Code,Example of Palindrome Number,Program of Java Palindrome Number

#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
I'm asking why didn't you just do this:
public boolean isPalindrome(String check)

{

    return new StringBuilder(check).reverse().toString().equals(check);

}
instead of the complicated mathematical method?
Wow I changed my sig!

#5
arunjib

arunjib

    Learning Programmer

  • Members
  • PipPipPip
  • 76 posts
thanks to all




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users