• Post Reply Bookmark Topic Watch Topic
  • New Topic

I've written code to find palindrome no between 1 and 100,as shown below  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Its output is :
1 is a palindrome.
2 is a palindrome.
3 is a palindrome.
4 is a palindrome.
5 is a palindrome.
6 is a palindrome.
7 is a palindrome.
8 is a palindrome.
9 is a palindrome.

in this program, my logic was to find the reverse of a number and compare it with the original number.If it is same, then the number is a palindrome no.,otherwise not.
Can anyone tell me that why it is not working for any 2 digit no ??

 
Sheriff
Posts: 4931
334
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Add after line 21 this:


So, the answer to your question is, because rev and i never equal. After adding this line and running code again you'll see what I'm talking about.
 
Marshal
Posts: 4051
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might be simpler to represent the number as a String and compare it against the reverse of itself.
 
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's another improvement you can make to your code: You don't need a special case for single digit numbers. The part in your else clause will work fine for all cases, after you've fixed it. You can also use compound assignment expressions and remove a variable:
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem with the code was that rev was not getting reset which was leading to invalid reversal.

Adding line 6 would fix the issue. Please find the code below:

[code removed by moderator, see below]
 
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code has been removed because it is a complete solution.  In Beginning Java, we guide to OP to the solution with hints, questions, and sometime code snippets.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A better fix is to declare variables only when you need them. Declaring all variables at the top of a method is old-school programming that we've come to expect from languages like Pascal, but it's not fit for modern languages.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!