Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • 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

 
akshat khandelwal
Greenhorn
Posts: 6
  • 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 ??

 
Liutauras Vilda
Marshal
Posts: 3961
214
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.
 
Tim Cooke
Marshal
Posts: 3698
187
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.
 
Stephan van Hulst
Saloon Keeper
Posts: 7190
118
  • 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:
 
Vinod Khatrii
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]
 
Knute Snortum
Sheriff
Posts: 3612
86
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: 7190
118
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!